Jquery selector looping vs using function each

  • Do these two code snippets have the same thing? If so, when should you use each other? (also, when you need to do something involving i or value )

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

    against.

     $("foo").empty(); 
  • In the general case, we can assume that $("foo").someMethod() means "execute somemethod() for each element that corresponds to the selector, except that the method name is each ? (I.e., each is a special case)

+8
jquery
source share
2 answers

Assuming you mean jQuery functions for stocks, yes, the two pieces of code are identical.

You should use the each() function either when working with the index, or to prevent a long chain of functions.

Your understanding of $('foo').someMethod() is true for jQuery methods. But be careful, some plugins may handle the selector differently or affect only the first matched element.

+4
source share

Yes, most jQuery functions are created like this.

Take a look at the sample code:

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

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

$(selector).someMethod();

not

 $(selector).each(function() { $(this).someMethod(); }); 
+3
source share

All Articles