Ishan Soni
Ishan Soni

Reputation: 273

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/

Upvotes: 8

Views: 111

Answers (3)

Ani Menon
Ani Menon

Reputation: 28199

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

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

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

Upvotes: 5

Aalok Mishra
Aalok Mishra

Reputation: 196

You can go through the following link to get a better handle of :eq & .eq() https://forum.jquery.com/topic/eq-vs-eq

If you still have doubts, here is a possible duplicate of this question: Difference between ":eq()" and .eq()

Upvotes: 0

Related Questions