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.

3
  • The question is why would you want to do that? The point of standards is so that things will have consistent behavior amongst browsers.
    – user1508519
    Commented Aug 7, 2013 at 19:24
  • If you reached such a situation you are gonna have to innovate fundamentally!
    – beck03076
    Commented Aug 7, 2013 at 19:24
  • You can, sure, but you definetly should'nt to my opinion. Commented Aug 7, 2013 at 19:27

3 Answers 3

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.

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.

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.