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/
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")
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With