The difference between $ (this) .find ("li") and $ ("li", $ (this))

When creating a jQuery plugin, I find a lot of use

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

to select the current item. How it works? Since while writing jQuery snippets I wrote

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

Can someone explain for a better understanding? Link to this code here .

+4
source share
2 answers

Both are doing the same. In fact, if you dig deep enough, you will find that $("li:even", obj) ends with a call to obj.find("li:even") .

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

I remember seeing a comment from one of the main jQuery developers on a ticket with a question that they consider when dropping the version of $() that takes a starting point.

+4
source

$ ("li: even", obj)

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

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

All four will have the same result.

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

or

 $("li:even", this) 

or

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

or

 $(this).find("li:even"); 
+3
source

All Articles