Web Development Ninjas Question:

Explain me what is the each() function in jQuery? How do you use it?

Tweet Share WhatsApp

Answer:

each() function is like an Iterator in Java, it allows you to iterate over a set of elements. You can pass a function to each() method, which will be executed for each element from the jQuery object, on which it has been called. This question sometime is asked as a follow-up of the previous question e.g. how to show all selected options in alert box. We can use the above selector code to find all the selected options and then we can use the each() method to print them in an alert box, one by one, as shown below:

$('[name=NameOfSelectedTag] :selected').each(function(selected){
alert($(selected).text());
});

The text() method returns text for that option.

Download Ninjas Web Developer PDF Read All 58 Ninjas Web Developer Questions
Previous QuestionNext Question
Tell me what is $() in jQuery library?Tell me what is method chaining in jQuery? What is the benefit of using method chaining?