Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.each(function(index, value){}); What is value?

Tags:

jquery

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?

like image 807
cadence441 Avatar asked Jun 10 '12 12:06

cadence441


People also ask

What is each () function in jQuery?

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.

What is the use of each () method?

The each() method specifies a function to run for each matched element.

Can we use foreach in jQuery?

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.

What is $() in jQuery?

$() = 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.


1 Answers

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:

like image 143
Sampson Avatar answered Oct 16 '22 06:10

Sampson