Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery selector looping vs using function each

Tags:

jquery

  1. Do these two snippets of code do identical things? If yes, when should one be used over the other? (besides when you need to do something involving i or value)

    $("foo").each(function(i,value) {
        $(this).empty();
    });
    

    vs.

    $("foo").empty();
    
  2. In general can it be assumed that $("foo").someMethod() means "run somemethod() on each element that matches the selector, except if the name of the method is each? (ie each is a special case)

like image 484
wal Avatar asked Oct 16 '12 12:10

wal


People also ask

What is the use of 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.

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.

How do I get out of each loop in jQuery?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.

Which loop is faster in jQuery?

each() loop : Lower performance compare to other loops (for games/animations/large datasets) Less control over iterator (skip items, splice items from list, etc). Dependency on jQuery library unlike for, while etc loops!


2 Answers

Assuming you're referring to stock jQuery functions, yes, the two snippets of code are identical.

You should use the each() function either when you want to work with the index, or to prevent long function chaining.

Your understanding of $('foo').someMethod() is true of jQuery methods. But be warned, some plugins may handle the selector in a different manner, or only affect the first matched element for example.

like image 71
BenM Avatar answered Oct 02 '22 20:10

BenM


Yes, most jQuery function are designed like this.

Look at the code example:

$.fn.someMethod = function() {
   return this.each(function() {
      do_something(this); 
   });
};

So even you could use .each again, you should just use:

$(selector).someMethod();

not

$(selector).each(function() {
  $(this).someMethod();
});
like image 40
xdazz Avatar answered Oct 02 '22 20:10

xdazz