Sunil Soundarapandian
Sunil Soundarapandian

Reputation: 158

Difference between $(this).find("li") and $("li", $(this))

While creating a jQuery plugin I find many uses of

var obj = $(this);     
$("li:even", obj)

to select the current Item. How does this work? Because while writing jQuery snippets I used to write

 $(this).find("li");

Can someone explain for better understanding? Reference to this code is here.

Upvotes: 4

Views: 3115

Answers (2)

Adil
Adil

Reputation: 148150

$("li:even", obj)

In the above statement the context is passed to selector. This is equalent to $(this).find("li:even");

According to jQuery documentation the syntax for selector is jQuery( selector [, context ] )

All the four will bring the same result.

var obj = $(this);
$("li:even", obj) 

or

$("li:even", this) 

or

$("li:even", $(this)) 

or

$(this).find("li:even");

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074949

The two do the same thing. In fact, if you dig deep enough, you'll find that $("li:even", obj) ends up calling obj.find("li:even").

You probably know that (that variant of) the $() function looks up elements in the DOM. The form that accepts that second argument just gives it a starting point, telling it to only look for descendants of the elemnts in the jQuery set you provide as the second argument. Which is, of course, what find does.

I remember seeing a comment from one of the jQuery main devs on an issue ticket that they're considering dropping the version of $() that accepts the starting point.

Upvotes: 4

Related Questions