jquery each - stackoverflow demo
by ian_smithz
HTML
https://stackoverflow.com/questions/10968555/jquery-eachfunctionindex-value-what-is-value
JavaScript
//There are two each methods in jQuery. One is for cycling over a jQuery object which contains many matches. //For instance, suppose we wanted to find all paragraphs on the page:
$("p").each(function(){
// Do something with each paragraph
});
//Secondly, there is a more generic each for iterating over objects or arrays:
var names = ["Jonathan", "Sampson"];
$.each(names, function(){
// Do something with each name
});
//When jQuery cycles over the elements in either of these examples, it keeps count of which object it's //currently handling. When it executes our anonymous function, it passes in two parameters - the current value //we're on (index), and that object (value).
var names = ["Jonathan", "Sampson"];
$.each(names, function(index, value){
alert( value + " is " + index );
});
//Which outputs "Jonathan is 0", and "Sampson is 1" since we're using a zero-based index.
//But what about our native jQuery object?
$("p").each(function(index, value){
alert( value.textContent ); // The text from within the paragraph
});
//In this case, value is an actual HTMLParagraphElement object, so we can access properties like textContent //or innerText on it if we like: