I am learning jQuery from a book called Head First jQuery. The book is very easy to learn from. The point is, there is an .each()
function(included in image which I scanned from the ) which has a function() parameter. The function() parameters are index
and value
. The index is explained on the page, but what about the value? And also, since it is an anonymous function(which cannot be reused) how does it take any parameters?
each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
The each() method specifies a function to run for each matched element.
each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With