undefined is our god
undefined is our god

Reputation: 511

Difference between getting jQuery's $(selector).each() 'element' parameter, vs $(this)

Is there any difference (related to performance or something else) on getting jQuery .each()'s element parameter

$(".element").each(function(i, e){
   console.log("element: " + $(e));
});

and using $(this)?

$(".element").each(function(){
   console.log("element: " + $(this));
});

I've done several tests and programatically I didn't noticed any difference. I'm always using $(this) because it's the standard used on most applications.

Upvotes: 0

Views: 63

Answers (2)

David Thomas
David Thomas

Reputation: 253318

While there's no practical difference in your example, the availability of e within an enclosed function, or method-call, is a useful feature.

For example:

$('.element').each(function(i, e) {
    $('.otherElement').text(function(index, element){

      // in this method, $(this) is an element from
      // the $('.otherElement) collection (also $(element));
      // to access elements of the $(`.element') collection
      // we can no longer use $(this), but we can still use
      // $(e) (or e):

      return $(e).eq(index).text(); // will set the text of the $(element)
                          // to the text of the $(e) element
    });
})

Upvotes: 1

James Thorpe
James Thorpe

Reputation: 32202

No, there's no practical difference. In the source of each, we can see that the same thing (obj[i]) is passed to call to be used as both this and the 2nd parameter within your callback:

value = callback.call(obj[i], i, obj[i]);

Upvotes: 4

Related Questions