17

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")
tkbx
  • 15,602
  • 32
  • 87
  • 122

3 Answers3

39

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)
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 2
    Technically if you want the nth element, you select the n-1 with eq() since it's zero-based. – j08691 Mar 18 '13 at 16:36
  • @j08691 Yes. I edited (please let your comment in case it's not clear for OP). In fact what is wrong isn't the code but the sentence as it's probable OP wanted in fact the element of index n. – Denys Séguret Mar 18 '13 at 16:38
6

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.

Eli
  • 14,779
  • 5
  • 59
  • 77
4

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.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531