Home > database >  Does jQuery selector iterates through all elements? [closed]
Does jQuery selector iterates through all elements? [closed]

Time:09-16

I have multiple links on my page and I wan to create the same event handler for all of them.

In the first example I am just using a selector and it creates the event handler correctly for both of the links:

$(document).ready(function () {
    $('.link').on('click', function () {
        alert($(this).text()   ' was clicked');
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href='#' class='link'>Link1</a>
<a href='#' class='link'>Link2</a>

In the second example, I iterate through each element and create the event handler for every single one of them:

$(document).ready(function () {
    $('.link').each(function(){
      $(this).on('click', function(){
        alert($(this).text()   ' was clicked');
      });
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href='#' class='link'>Link1</a>
<a href='#' class='link'>Link2</a>

Both are producing the same result, but why? Is there any difference between these two methods? Is either one preferred?

If jQuery selector already iterates through all the elements, then I guess there is no point using each() in the example? Does jQuery selector always iterate the elements or are there particular scenarios? If jQuery selector always iterates through all the elements, then why using .each?

CodePudding user response:

The concept you're looking for is called Implicit iteration.

It is mentioned in the jQuery Documentation for .each():

Note: most jQuery methods that return a jQuery object also loop through the set of elements in the jQuery collection — a process known as implicit iteration. When this occurs, it is often unnecessary to explicitly iterate with the .each() method.

Selecting something using $('.link') returns a selection, which is like a list of items meeting the criteria laid out in your selector (Elements with the class link in this case). The selection itself does not iterate over anything, it just provides you with a list of items.

Depending on what you do with the Selection afterwards, implicit iteration might take place. That is for example the case with most setters (in your case .on()). Setters will iterate over the selection and apply to all items in it.

Functions that don't implicitly iterate (Usually Getters) are where you want to iterate yourself using .each() if you need them run on multiple items.

  • Related