wal
wal

Reputation: 17759

jquery selector looping vs using function each

  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)

Upvotes: 8

Views: 256

Answers (2)

xdazz
xdazz

Reputation: 160963

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();
});

Upvotes: 3

BenM
BenM

Reputation: 53246

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.

Upvotes: 4

Related Questions