开发者

I have$('.class:first'), I want $(.class:fourth') using jquery

I can select the first item in the div using

$('.class:first')

Now since I w开发者_StackOverflow社区ill 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


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.


$('.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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜