zsharp
zsharp

Reputation: 13756

repeating id's of element children

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?

Upvotes: 1

Views: 209

Answers (5)

Borgar
Borgar

Reputation: 38644

Read the spec:

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

Upvotes: 3

marcgg
marcgg

Reputation: 66436

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.

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361585

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.

Upvotes: 9

devXen
devXen

Reputation: 3132

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.

Upvotes: 1

Kelly Robins
Kelly Robins

Reputation: 7288

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.

Upvotes: 2

Related Questions