Can multiple different HTML elements have the same ID if they're different elements?
No.
Element IDs should be unique within the entire document.
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.
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:
- 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!