tags:

views:

69

answers:

3

Hello,

I can select the first item in the div using

$('.class:first')

Now since I will have random id values, and the class remains the same, I want to access the id of the fourth element, will it be something like this

$('.class:fourth')

using jQuery.

Thanks Jean

+6  A: 

$('.class:nth(4)')

UPDATE:

Actually it's $('.class:nth-child(4)')

UPDATE2:

The correct answer is given by @cletus with a great explanation of the differences between nth-child and eq selector:

$('.class:eq(3)')

Please mark his answer as correct.

Darin Dimitrov
hah, easy one :)
danp
THANKS..............
Jean
@danp not easy, when no clue..
Jean
for reference -> http://css-tricks.com/pseudo-class-selectors/
ILMV
@Jean this answer is incorrect. See my answer.
cletus
@cletus I used $('.class:nth(4)')It works fine
Jean
A: 

Or you can do $("expr").eq(2) - detail here

danp
+6  A: 

There are several ways of doing this. Firstly you can use the :eq(n) pseudo-element:

$(".class:eq(3)")...

:eq(n) is zero-based so :eq(3) is the fourth instance. You can also use eq():

$(".class").eq(3)...

The correct answer is not:

$(".class:nth-child(4)")...

What's the difference? The last one finds all elements that have a class of "class" that are the fourth child of something. That could be zero or many elements.

cletus
@cletus +1, thanks for this great explanation.
Darin Dimitrov
`.eq(3)` should be used in preference to the selector version. `:eq` is not a standard CSS selector; it is a jQuery hack, which will force the selector to be evaluated using the (slow) JS Sizzle library instead of the (fast) built-in `querySelectorAll` method present in modern browsers.
bobince