views:

62

answers:

5

Is it ok to have id names for children of an element the same as the ids of children of another element provided the parent id is different? Any potential conflict?

+2  A: 

It is very bad practice and likely to cause errors. A better solution would be to use classes to distinguish the child objects and then descend from the parent ID to locate the element you are looking for.

apocalypse9
+1  A: 

The ID should always be unique regardless in the context of HTML or Javascript. You are much better off with an unique identifier. For example, you have multiple elements with id named "foo"; in document.getElementById("foo") will only return the first instance by that id.

Chenster
+9  A: 

No, element ids should be unique throughout the entire document. document.getElementById() won't work right with duplicate ids (obviously, as it only returns one element). Now your page will probably work fine with the duplicate ids, it's not like the browser will crash or refuse to render the page or anything, but it's not correct HTML.

If you need non-unique identifiers use the class attribute. That's exactly what it's for, to tag multiple elements with the same name.

John Kugelman
+1  A: 

If you've got different DOM elements with the same ID, it will lead to troubles at some point... don't do it even thought it might work.

marcgg
+3  A: 

Read the spec:

This attribute [id] assigns a name to an element. This name must be unique in a document.

Borgar
rtfm ftw
marcgg