Multiple identical element identifiers in HTML5 - how should this work with scripts?

I answered hundreds of jQuery questions. One of the common beginner mistakes is the use of several element identifiers, for example:

<div id="a">....</div> <div id="a">....</div> 

Then they will do something like this and ask why it is not working properly:

 $('#a').hide(); 

I usually answer:

 IDs must be unique 

... to which someone always answers:

But not in HTML5!

Question So, if multiple identical identifiers are allowed in HTML5, how should scripts handle them, or should we still avoid using multiple identical identifiers for elements?

+7
source share
2 answers

Just quote HTML5

The id attribute indicates its unique element identifier (ID). [DOMCORE]

The value must be unique among all identifiers in the home subtree element and must contain at least one character. The value should not contain any whitespace characters.

I assume that in a general sense, the ID might be wrong. However, it must be valid in the context of a subtree.

Home subtree:

A node home subtree is the subtree root in this root directory of the node element. When a node is in a document, its home subtree is the Document Tree

+12
source

I vote to avoid using multiple identical identifiers. Jquery returns an array of elements based on a selector that will hide the misuse of this convention .

When using identifiers as a jquery selector, only 1 element is returned: Jquery Docs

I will continue to keep my identifiers unique. It just makes development easier.

+3
source

All Articles