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
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 have selected and still do select the first element with a given ID, when calling getElementById
. Most libraries that find elements by ID inherit this behavior. 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, 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:
The power is yours!