jQuery nth item of id/class [closed]

2020-08-16 03:08发布

I'd like to use the id selector:

$("#id")

Is there a way to do this to only the nth element with that ID on the page? i.e.

$("#id:n")

标签: jquery
3条回答
姐就是有狂的资本
2楼-- · 2020-08-16 03:43

You can use the :eq(n) selector fetch the n-th item, but id should be unique.

You should use the class attribute to group similar elements.

查看更多
forever°为你锁心
3楼-- · 2020-08-16 03:55

There can be only ONE element with a given id in a page.

From the HTML norm :

There must not be multiple elements in a document that have the same id value.

Now suppose you want to get the nth element with a given class in your page, you may use eq :

$('.myclass').eq(index)
查看更多
相关推荐>>
4楼-- · 2020-08-16 04:02

You can do like this:

$("#id:eq(n)")

But like @dystroy answer, it should be only 1 id in a page so you better using class.

查看更多
登录 后发表回答