Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple identical element IDs in HTML5 - how is this supposed to work with scripts? [closed]

I've answered hundreds of jQuery questions. One of the common newbie mistakes is to use multiple element IDs, like so:

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

Then they'll do something like this and ask why it doesn't work as expected:

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

I usually respond with:

IDs must be unique

...to which someone always responds with:

But not in HTML5!

The question: So if multiple identical IDs are allowed in HTML5, how are scripts supposed to handle them, or should we still be avoiding the use of multiple identical element IDs?

like image 445
Diodeus - James MacFarlane Avatar asked Apr 02 '13 21:04

Diodeus - James MacFarlane


People also ask

What happens if multiple HTML elements have the same ID?

The id must be unique. There can be only one element in the document with the given id . If there are multiple elements with the same id , then the behavior of methods that use it is unpredictable, e.g. document. getElementById may return any of such elements at random.

Can we use same ID multiple times in HTML?

The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.

How many times can we use the same ID on a HTML document?

You may only use the same id attribute value once per html page, so save it for important major sections of your page. The id selector in CSS has a high specificity level and therefore overrules most other CSS selectors (more on this later).

Can you have multiple IDs in JavaScript?

No it is not possible. ID always refer to uniqueness.


2 Answers

Just quoting from HTML5

The id attribute specifies its element's unique identifier (ID). [DOMCORE]

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

I guess in the general sense, ID may be a misnomer. However, it should be valid within the subtree context.

A home subtree is:

A node's home subtree is the subtree rooted at that node's root element. When a node is in a Document, its home subtree is that Document's tree

like image 168
karthikr Avatar answered Oct 26 '22 23:10

karthikr


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

When using IDs as the jquery selector only 1 element is returned: Jquery Docs

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

like image 34
bradj Avatar answered Oct 27 '22 00:10

bradj