Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 633
Ishan Soni Avatar asked May 27 '16 08:05

Ishan Soni


2 Answers

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").

like image 193
Denys Séguret Avatar answered Oct 19 '22 05:10

Denys Séguret


alert($("ul li:eq(0)").length); => length of first li within ul, :eq(0) always returns 1 or 0 elements.

alert($("ul").find("li:eq(0)").length); => Number of times an li exits within ul

alert($("ul").find("li").eq(0).length); => length of number of times li exits within ul

like image 39
Ani Menon Avatar answered Oct 19 '22 05:10

Ani Menon