What is the definition of the :nth
pseudo class ?
I can't find any jQuery or CSS documentation on it, but it seems to exist:
var $list = $('<ul><li>1</li><li>2</li><li>3</li></ul>');
$list.find('li:nth(2)').text();
Returns: "3"
,
While:
$list.find('li:nth-of-type(2)').text();
$list.find('li:nth-child(2)').text();
both return "2"
What is this pseudo class? Can someone point me to some documentation on it?
Contrary to other answers, :nth()
is not a CSS pseudo-class selector.
It's a little-known positional selector used in the Sizzle engine:
:nth:
Finds thenth
element on the page.
You'll find the above definition here in the Github documentation for Sizzle.
The reason that nth()
and your other selectors select different elements is because nth()
is a zero-based index selector, while the CSS selectors are one-based index selectors.
It's understandable how this can be confusing as most would assume that nth()
would keep some kind of consistency with the similarly-named CSS pseudo class selectors such as nth-child()
and nth-of-type()
- however, as mentioned, they aren't actually related.
Yes. In fact, it seems as though nth() is exactly the same as eq():
Expr.pseudos["nth"] = Expr.pseudos["eq"];
This old mailing list conversation (2007) implies John Resig planned to remove the :nth()
selector due to this:
"I've searched the groups but I can't seem to find any related talk on this. What, if any, is the difference between using
:eq(n)
and:nth(n)
? I'd like to know before I start standardizing on one or the other. Thanks." - Matt Penner"They're the same, so you can use whichever you prefer. From jquery.js:
nth: "m[3]-0==i",
eq: "m[3]-0==i"
" - Karl Swedberg"Huh... I should probably nuke
:nth()
." - John Resig
But, as you've noticed, the removal of the :nth()
selector never materialised (as of 2013, anyway).
HTML:
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
jQuery:
$('p:nth(2)').text(); // Returns 3 as zero-based index.
$('p:eq(2)').text(); // Returns 3 as zero-based index.
$('p:nth-child(2)').text(); // Returns 2 as one-based index.
$('p:nth-of-type(2)').text(); // Returns 2 as one-based index.
jsFiddle version here.
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