Can multiple different HTML elements have the same ID if they're different elements?
Solution 1
No.
Element IDs should be unique within the entire document.
Solution 2
I think there is a difference between whether something SHOULD be unique or MUST be unique (i.e. enforced by web browsers).
Should IDs be unique? YES.
Must IDs be unique? NO, at least IE and FireFox allow multiple elements to have the same ID.
Solution 3
Can multiple elements have the same ID?
Yes - whether they are the same tag or not, browsers will render the page even if multiple elements have the same ID.
Is it Valid HTML?
No. This is still true as of the HTML 5.1 spec. However, the spec also says getElementById
must return the first element with the given ID, making the behavior not undefined in the case of an invalid document.
What are the consequences of this type of invalid HTML?
Most (if not all) browsers select the first element with a given ID, when calling getElementById
. Some libraries that find elements by ID inherit this behavior, while newer libraries (as gman points out in his answer) will use the more explicit querySelector
and querySelectorAll
methods, which unambiguously select either the first or all matching elements, respectively. Most (if not all) browsers also apply styles assigned by id-selectors (e.g. #myid
) to all elements with the specified ID. If this is what you expect and intend, then there are no unintended consequences. If you expect/intend something else (e.g. for all elements with that ID to be returned by getElementById
, or for the style to apply to only one element) then your expectations will not be met and any feature relying on those expectations will fail.
Some javascript libraries do have expectations that are not met when multiple elements have the same ID (see wootscootinboogie's comment about d3.js)
Conclusion
It's best to stick to the standards, but if you know your code works as expected in your current environments, and these IDs are used in a predictable/maintainable way, then there are only 2 practical reasons not to do this:
- To avoid the chance that you are wrong, and one of the libraries you use actually does malfunction when multiple elements have the same ID.
- To maintain forward-compatibility of your website/application with libraries or services (or developers!) you may encounter in the future, that do malfunction when multiple elements have the same ID - which is a reasonable possibility since this is not, technically, valid HTML.
The power is yours!
Solution 4
Even if the elements are of different types it can cause you some serious problems...
Suppose you have 3 buttons with the same id:
<button id="myid" data-mydata="this is button 1">button 1</button>
<button id="myid" data-mydata="this is button 2">button 2</button>
<button id="myid" data-mydata="this is button 3">button 3</button>
Now you setup some jQuery
code to do something when myid
buttons are clicked:
$(document).ready(function ()
{
$("#myid").click(function ()
{
var buttonData = $(this).data("mydata");
// Call interesting function...
interestingFunction();
$('form').trigger('submit');
});
});
What would you expect? That every button clicked would execute the click event handler setup with jQuery. Unfortunately it won't happen. ONLY the 1st button calls the click handler. The other 2 when clicked do nothing. It is as if they weren't buttons at all!
So always assign different IDs
to HTML
elements. This will get you covered against strange things. :)
<button id="button1" class="mybtn" data-mydata="this is button 1">button 1</button>
<button id="button2" class="mybtn" data-mydata="this is button 2">button 2</button>
<button id="button3" class="mybtn" data-mydata="this is button 3">button 3</button>
Now if you want the click event handler to run when any of the buttons get clicked it will work perfectly if you change the selector in the jQuery code to use the CSS
class applied to them like this:
$(document).ready(function ()
{
$(".mybtn").click(function ()
{
var buttonData = $(this).data("mydata");
// Call interesting function...
interstingFunction();
$('form').trigger('submit');
});
});
Solution 5
No. two elements with the same id are not valid. IDs are unique, if you wish to do something like that, use a class. Don't forget that elements can have multiple classes by using a space as a delimeter:
<div class="myclass sexy"></div>
Related videos on Youtube
omninonsense
Updated on April 16, 2022Comments
-
omninonsense about 2 years
Can multiple HTML elements have the same ID if they're of different element types? Is a scenario like this valid? Eg:
div#foo span#foo a#foo
-
Paul Creasey about 13 yearsWhile sometimes possible, it's never valid.
-
Lukasz Matysiak over 6 yearsWith all the above being said it is worth to note that it is likely to come across multiple same IDs in a document with user-agent-created content (think frameworks, mv*, react, polymer...). That's if anyone was wondering why a very professional looking XYZ site is full of such bad practice coding.
-
Richard Abey-Nesbit over 3 yearsThe comment from @PaulCreasey is a good way to answer this problematic question. The question title and body do not match; each of them are reasonable yes or no questions but with different correct answers - this could catch out people who aren't paying attention. There's a meta question about how to resolve question mismatches like this, no answers though as of yet: meta.stackoverflow.com/questions/256732
-
omninonsense over 3 yearsHi @Tidorith! Thanks for commenting. I'm open to suggestion on changing either the title or the body if you have an idea. The original question was asked out of curiosity. Some codegen tool (I think it might've been some Microsoft UI library) was generating elements with identical IDs. I tried reading the spec and testing it out in browsers, but was left confused since browsers seemed to allow it, while the spec said no.
-
omninonsense over 3 years@Tidorith Edited the question body a bit. Hope it's better now!
-
-
omninonsense over 11 yearsSo does Chrome (v22 at the time this comment was written). :D
-
corsiKa over 11 yearsWhat are the consequences of not doing so?
-
Kevin B almost 11 yearsUnless you use a more complex selector, such as
div#one
That of course doesn't change the fact that it's invalid. -
mrooney almost 11 years@corsiKa the consequence is undefined behavior, for example, what does document.getElementById("#foo") or $("#foo") return when there are multiple #foos? You'll run into problems being able to work with these elements from JS, pass them as selectors to libraries/APIs/Flash, etc.
-
Jared almost 11 yearsMicrosoft Outlook builds their webapp like this. It's annoying as hell. How would I reference a specific DIV if there are ones with the same ID?
-
leo about 10 years
-
BJury almost 10 years@leo however this is the real world where browsers don't conform fully to the standards. In this case it could be a good thing, as there is no reason to enforce unique IDs.
-
Max Yari over 9 yearswhy even use multiple similar id's when you got class for this purpose?
-
Cheesus Toast over 9 yearsI think I have found a situation where this seems to occur. If you are using radio buttons on ASP.NET MVC 5 Razor it seems to produce the same ID for each button. I think this may be how the controller deals with input because the id is the same as the ActionResult input parameters. It does not seem to care as long as it gets the right value. I believe there is a way around it but it seems to work OK (but I am not happy with multiple html IDs!).
-
Alen Siljak over 9 yearsYes, multiple IDs can, in practice, be replaced by using classes. However, classes are intended for applying styles, not identifying elements, making the scope of names much wider and therefore likely to overlap. Especially if using 3rd party libraries. Id as 'identifier' is not intended to be multiplied so there is clearly a need for something in between. The practical use is componentization of sections of a page/dom into separate logical units. Using (at least) 2-layer identification is hence required.
-
Dibyanshu Jaiswal about 9 yearsPossibly this answer is true, I am saying this from experience.
-
wootscootinboogie about 8 yearsRecently had a bug with d3.js and click event handling with multiple, identical IDs. What I observed was the first instance of the ID received the action, even if it was invoked by the second ID. E.g., click on the second instance of id1, and the first instance of id1 would receive the action (change color, text, etc.).
-
Jeremy about 8 yearsWhilst it may be considered bad practice or even invalid HTML 5 by validators, having multiple ID's is certainly possible within the same HTML document. Therefore this answer is not the correct one.
-
Koshinae about 8 yearsA link to the spec: html.spec.whatwg.org/multipage/dom.html#the-id-attribute
-
Dmytro over 7 yearsSo it is completely reasonable to have #content and #myDiv #content for a brief period of time?
-
Dmytro over 7 yearswhat if I have a "#content" which I already have referenced in a variable, and a #my-div #content which I only have for a few moments after which I remove the referenced node and forget its variable, after which the #div #content performs a myDiv.outerHTML = myDiv.innerHTML to replace the original. This saves the need to hard copy all styles and contents of #content into #decoy and do the same thing. This makes sense when doing transitions.
-
Nick Steele over 7 yearsYes, it's valid. SVG files contain ID names and can even mess up applications that don't account for the possibility of multiple ID names (if you make a G tag with an id, it becomes part of the DOM, so drawing an SVG on screen can introduce multiple id tags, even if you aren't aware it's happening, right on your site.
-
mltsy almost 7 yearsIn HTML5, the spec for
getElementById
actually does define that the first element with the given ID must be returned (which is how all browsers currently handle the situation anyway) - see my answer below for more. -
psycho brm almost 7 yearsGood point. Although the dynamically generated content that is supposed to be inserted into another page should avoid ids altogether. Ids are like globals in programming languages, you can use them, and there are valid cases where it's a nice hack that simplifies things. It's a nice practice to consider doing things right before doing hacks.
-
Bilow over 6 yearsThe
:target
selector does only work on ids. Can't use classes. Isn't it a valid scenario ? -
Karan Kaw over 6 yearsThis means that, even if I use 'append' to add multiple element of same id, DOM only considers first element to be real, ideally 1 ID = 1 Element
-
Spyryto over 6 yearsNope. The answer to the question "Is this valid?" does not necessarily have to match the answers to the questions "Do I need this?", "Do I wish this was valid?" or even "Does this dirty hack work in current implementations of the spec?"
-
Dawied almost 6 yearsWhat would be an alternative in case you want to group some elements using an identifier?
-
SLaks almost 6 years@Asimov: Classes or attributes.
-
MLK.DEV over 5 yearsUnder the current specification, the
id
attribute is for "uniquely identifying" a tag. Re-using the sameid
within the same document is considered invalid. dom.spec.whatwg.org/#concept-id -
PoloHoleSet over 5 yearsWhat about for something like bootstrap menu list items (<li>)? I have the same menu items, one that shows up in a standard menu, one that only shows up in an expanded menu in mobile view. They are, for all intents and purposes, the same item, and I want the same behavior for them if there is any object interaction. I have a plug in that isn't working because it won't assign an ID for the WordPress menu item in the mobile menu.
-
Dhruv Singhal over 5 yearsif I have two fields having same id, how to retrieve data collectively from those fields? Pardon me for so late comment, but I am having this issue for 2-3 hours and can't seem to find a working solution for it
-
SLaks over 5 years@DhruvSinghal: Don't do that. IDs should be unique.
-
Dhruv Singhal over 5 yearsOK so let me rephrase by question... I am NOT using ids. How can I achieve that now?
-
SLaks over 5 years@DhruvSinghal: Use classes or
data-
attributes or anything else that can be selected by a CSS selector /querySelector()
. -
Dhruv Singhal over 5 yearsThanks, I used getElementByNames and got the desired result
-
user2988142 over 5 years@DhruvSinghal:
document.querySelectorAll('#foo')
could be used to retrieve all elements with same id's. (at least in Firefox) -
Dhruv Singhal over 5 years@user2988142 as others mentioned, I will not be relying on duplicate IDs because I have to make the project browser independent. So getting elements by names has been better way for doing so for me (since I am using form)
-
MrWhite about 5 years"the id tag allows spaces" - Although, according to the spec, the "The value must not contain any space characters."
-
Nick Steele about 5 yearsI agree. However, there is the spec, and there is how the browsers operate. Browsers historically treat the spec as something of a goal, but have not been strict on many of the items. I think they do this because if they met the spec it would break lots of existing sites or something. I mention at top that although these things work, they are invalid.
-
Richard Abey-Nesbit over 3 years@Spyryto There's a bit of an issue here in that the question title and the question body are asking different questions. To someone looking for an answer to the title, "Can multiple different HTML elements have the same ID if they're different elements?", the answer "no" is wrong, potentially dangerously so. In reality they absolutely can - but they're not supposed to, and indeed it is not valid for them to do so.
-
omninonsense over 3 yearsInteresting answer, thanks! I've observed generated duplicated IDs in some third party code (I forgot what it was now), and while I knew it would work in most browsers, I was curious if there are any serious implications/downsides to this, and whether it was actually valid since at the time I've believed it wasn't valid (and it's still not valid, but it turns out most clients are lenient).
-
gman over 3 yearsI would argue the spec is invalid. Given some of the largest sites on the planet are using the feature the spec should change to reflect what browsers are actually doing.
-
kofifus over 3 yearsthis is a totally wrong answer why is it marked ? the answer is yes and it can be quite useful
-
Liam over 2 yearsIf you don't write HTML according to the specifications then all bets are off. The browser and/or any js library can quite legitimately just break and it's your fault, not theirs
-
gman about 2 yearsThe spec you link to doesn't seem to say ids need to be unique in the document, only in that element's tree
-
mltsy almost 2 years@gman That's true - but as far as I know a document can only have one node tree at a given time. Of course if you're dealing with multiple documents, or multiple node trees not connected to a document, they can each have a copy of the same ID without being invalid. That seems like an esoteric technicality though. But only slightly more esoteric than the the conditions of validity for this case in general, since most modern libraries have no problem with duplicate IDs ;)