Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the :nth() pseudo-class selector in jQuery?

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?

like image 893
Walter Stabosz Avatar asked Jun 29 '13 17:06

Walter Stabosz


Video Answer


1 Answers

What is the :nth() selector?

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 the nth element on the page.

You'll find the above definition here in the Github documentation for Sizzle.

Why is it selecting different elements to :nth-child()/:nth-of-type()?

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.

So, :nth()'s functionality is actually closer to :eq() then?

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

Example usage:

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.

like image 165
dsgriffin Avatar answered Oct 02 '22 19:10

dsgriffin