Ishan Soni Ishan Soni - 5 months ago 20
jQuery Question

jQuery selectors confusing

I'd appreciate if someone also points me to theory sources so i can grasp it better.

Suppose i have the following HTML:

<ul>
<li>1</li>
</ul>

<ul>
<li>2</li>
</ul>


and this JavaScript code:

alert($("ul li:eq(0)").length);

alert($("ul").find("li:eq(0)").length);

alert($("ul").find("li").eq(0).length);


I get 1,2,1 as output. I can understand why I got 1 in the last case but why is the 1 and 2nd line of JavaScript code giving me different outputs.

fiddle :
https://jsfiddle.net/ishansoni22/pntz6kfx/

Answer

eq is a strange jQuery selector, not really consistent with the CSS based logic of most selectors (emphasis mine in this documentation extract):

The index-related selectors (:eq(), :lt(), :gt(), :even, :odd) filter the set of elements that have matched the expressions that precede them

In short, the eq(0) in the first case applies to the whole ul li.

$("anything :eq(0)") can return at most one element.

While in the second case, the "li:eq(0)" selector is applied by find to all matches of $("ul").