Why Is It a Bad Thing to Have Multiple HTML Elements With the Same Id Attribute

Can multiple different HTML elements have the same ID if they're different elements?

No.

Element IDs should be unique within the entire document.

What error will i get if i use the same ID for multiple HTML elements?

It would be invalid HTML.

In some environments, it may produce a console warning that multiple IDs in a single document is invalid. Harmless, but annoying.

It will prevent document.getElementById from working properly for those elements, because getElementById selects by ID, but there should only be one element with a given ID in the document. Similarly, it may prevent querySelector and querySelectorAll with ID selectors from working properly.

Using the same ID multiple times may well not break your application in most cases, but just because it might be doable in some circumstances doesn't mean it's a good idea. There's no reason to do it, so don't.

What are the side effects of using multiple instances of a single id name in HTML?

When you try and reference those elements from JavaScript it won't be able to resolve which element you are referring to. Depending on the specific JavaScript interpreter you are running on, you may either get errors, or undefined behaviour - both cases are undesirable.

The HTML spec states that Id's should be unique, so your HTML will be considered as invalid and may cause browsers to drop back into quirks mode rendering, or even totally refuse to render your page (although that's not likely, and all current browsers will render something - technically, if you don't follow the spec the browser is under no obligation to do anything but reject your page).

You should consider using class names instead if you want something to identify multiple elements by:

<div class="someClass">Some Content</div>
<div class="someClass">Some Other Content</div>

Blair has pointed out in the comments below that if you need to search for elements by class from JavaScript, you can speed the search up by going from the nearest element with an ID and also tell it what node type to look for. This can keep the access speed fast in a lot of cases, but doesn't break any rules on duplicate id's:

HTML:
<div id="myNearestID">
<div class="someClass">Some Content</div>
<div class="someClass">Some Other Content</div>
</div>

JavaScript+JQuery:
$('#myNearestID div.someClass')

Can same id address multiple elements in html?

It would be much, much better, in terms of both validity and semantics, if you wrote it using classes for your CSS instead:

<!DOCTYPE html>
<html>
<head>
<style>
.p01 {
color: blue;
}
</style>
</head>
<body>
<h1 class="p01"> Heading</h1>
<p>This is a paragraph.</p>
<p class="p01">This is a diff paragraph.</p>
<p>This is a paragraph.</p>
<p class="p01">I am different.</p>

</body>
</html>

Just because it works using id doesn't mean that it's correct. Imagine in a month that you want to add some javascript to get only one of those elements, you couldn't then use this:

var e = document.getElementById("p01");

because you couldn't be certain of what would be returned.

One way to look at it is by thinking of houses. Imagine that classes define the types of houses (apartments, bungalows, houses with pitched roofs etc), whereas ids define specific houses (John's house, Wendy's house etc).

Now imagine that you want to have all the bungalows painted red. Using the class, you can easily grab all of them at once, like:

var houses = document.getElementsByClassName("bungalow");
paint_red(houses);

Now imagine that you want to send a package to Wendy's house. In this case, you can find that specific house using its id:

var wendys_house = document.getElementById("wendy");
send_package_to(wendys_house);

Because you know that the id is unique, you can be certain that only Wendy's house will receive a package.

Why are duplicate ID values not allowed in HTML?

Specification says UNIQUE

HTML 4.01 specification says ID must be document-wide unique.

HTML 5 specification says the same thing but in other words. It
says that ID must be unique in its home subtree, which is basically
the document if we read the definition of it.

Avoid duplication

But since HTML renderers are very forgiving when it comes to HTML
rendering they permit duplicate IDs. This should be avoided if at all
possible and strictly avoided when programmatically accessing
elements by IDs in JavaScript. I'm not sure what getElementById
function should return when several matching elements are found?
Should it:

  • return an error?
  • return first matching element?
  • return last matching element?
  • return a set of matching elements?
  • return nothing?

But even if browsers work reliably these days, nobody can guarantee
this behavior in the future since this is against specification.
That's why I recommend you never duplicate IDs within the same
document.

This is an answer by Robert Koritnik at Software Engineering asked by danludwig

Question: Two HTML elements with same id attribute: How bad is it really?

Duplicate ids not allowed in HTML

That code is incorrect. Incorrect doesn't come in shades of grey. This
code violates the standard and is therefore incorrect. It would fail
validation checking, and it should. That said, no browser currently
on the market would complain about it, or have any problem with it at
all. Browsers would be within their rights o complain about it, but
none of the current versions of any of them currently do. Which
doesn't mean future versions might not treat this code badly.

~From Dan Ray

Duplicate ids and JavaScript

So if you use duplicate ids in your HTML many libraries will not work as expected. The most libraries will get the first id they find and return that element. When we look at pure JavaScript: the document.getElementById("idName"); should return in the case of multiple elements with the same id. It says it must return the first element, in tree order.

Is it semantically correct to have multiple (inner) elements with the same ID in one HTML page under different shadow roots?

Different shadow trees may contain elements with the same id since, as you said, shadow trees are essentially "microcosms".

Using the HTML Living Standard to prove this:

The id Attribute

When specified on HTML elements, the id attribute value must be unique amongst all the IDs in the element's tree and must contain at least one character. The value must not contain any ASCII whitespace.

To understand how the standard defines "tree", we turn to the DOM standard.

Trees

An object that participates in a tree has a parent, which is either null or an object, and has children...

The root of an object is itself, if its parent is null, or else it is the root of its parent. The root of a tree is any object participating in that tree whose parent is null.

The "tree" of an element consists of all its parents until it hits a "root" (and their children), and the element's children.

The standard makes a distinction between document trees and shadow trees because they have different roots:

A document tree is a node tree whose root is a document.

A shadow tree is a node tree whose root is a shadow root.

In other words, the root of a shadow tree is not the same as the root of the document, and hence they are in different trees for the sake of defining an id.

But to be thorough, we have to consider whether a document's children includes the shadow trees of its children. For that we turn to the definition of Node Tree.

It's harder to quote directly, but essentially a tree can either be a Document which contains Elements, or a DocumentFragment. Elements, meanwhile, are defined to contain either other Elements or CharacterData nodes, notably not DocumentFragments.

The final piece of the puzzle is that shadow roots are DocumentFragments, which are therefore not considered children of Documents for the sake of defining a tree.

Or to summarize:

  • An id must be unique within a tree.
  • A tree is all the elements between a root and its last children.
  • Document Trees and Shadow Trees have different roots.
  • Document Trees do not contain Shadow Trees as children.
  • Therefore, different Shadow Trees may contain the same id.
  • /li>


  • A similar answer on Stack Overflow.


Related Topics



Leave a reply



Submit