If I pick out a class with a jquery selector, like this: $(".listHeading")
and it returns m elements from the DOM, how do I pick out the nth of the m elements via a selector? I found this post, but it is not quite right because it says to call .eq()
which throws an error : jQuery nth item of id/class
Asked
Active
Viewed 60 times
-3

Community
- 1
- 1

bernie2436
- 22,841
- 49
- 151
- 244
-
2What's wrong with the answer in that post? – Barmar Feb 08 '14 at 02:34
-
1What's the error it throws? – dsgriffin Feb 08 '14 at 02:36
4 Answers
2
Just do
$(".listHeading")[n]
the order of the returned elements is the same as the order of their appearance in the DOM.

abl
- 5,970
- 4
- 25
- 44
0
You can get the nth element with the following code:
$(".listHeading").get(n-1);
Be careful, it won't return a jQuery object. So if you want a jQuery object, use:
$($(".listHeading").get(n-1))

Littm
- 4,923
- 4
- 30
- 38
0
$(".listHeading").eq(n)
to get a jquery object or
$(".listHeading")[n]
to get a dom element.

James Montagne
- 77,516
- 14
- 110
- 130
0
To use a selector to pick the element, use the :eq(n)
selector. It uses a zero based index, so for example to find the fourth element:
var el = $(".listHeading:eq(3)");

Guffa
- 687,336
- 108
- 737
- 1,005
-
1
-
@JamesMontagne: Good point, but the OP specifically asked for a way to do it with a selector. – Guffa Feb 08 '14 at 02:44
-
Why the downvote? If you don't explain what it is that you think is wrong, it can't improve the answer. – Guffa Feb 08 '14 at 12:55