简体   繁体   中英

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?

No, element id s should be unique throughout the entire document. document.getElementById() won't work right with duplicate id s (obviously, as it only returns one element). Now your page will probably work fine with the duplicate id s, 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.

Read the spec :

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

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.

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.

如果您具有相同ID的不同DOM元素,则有时会导致麻烦……甚至以为它可能会起作用就不要这样做。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM