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?
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.
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.
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).
No it is not possible. ID always refer to uniqueness.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With