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

后端 未结 16 1882
无人及你
无人及你 2020-11-21 05:30

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
16条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 06:08

    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:

    1. 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.
    2. 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!

提交回复
热议问题