0

I know ID's are meant to be unique, but I've got a quick question.

Can you use the same ID name on different elements? For example, could I have:

input#idname a#idname

...etc? Same ID, different element so long as I call them by their element tag in jQuery:

$("a#idname") $("input#idname")

etc?

Thanks.

Mark Eriksson
  • 1,455
  • 10
  • 19

3 Answers3

5

ID's are meant to be unique and an ID should exist only once on a webpage. The element with which you use the ID is irrelevant in your case.

Srikanth AD
  • 1,734
  • 2
  • 13
  • 19
2

You can, if you don't care about your document being valid. But there's a reason for caring about validity: If your document isn't conforming, there's no guarantee that JavaScript will do what you want it to.

HTML 5 says that document.getElementById(id) returns the first element with a given ID. I haven't seen anything requiring that querySelectorAll (which jQuery uses when it can) handle duplicate IDs differently than that, and before HTML 5, the behavior was altogether undefined anyway.

If you care about compatibility and keeping your JS straightforward, keep your IDs unique.

cHao
  • 84,970
  • 20
  • 145
  • 172
1

You shoud use unique ID's for each element. CSS, and DOM use this to identify elements. Duplicated IDs could generate some erros.

From W3C:

The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).

The id attribute is most used to point to a style in a style sheet, and by JavaScript (via the HTML DOM) to manipulate the element with the specific id.

Fals
  • 6,813
  • 4
  • 23
  • 43