Home > front end >  Is it okay to use two identical ID in HTML and SVG?
Is it okay to use two identical ID in HTML and SVG?

Time:10-13

On my page there are two id attribute with the same value:

<div id="main">
  <svg width="100%" height="100%" viewBox="0 0 192 192">
    <defs>
      <path id="main"  ..... 
    </defs>
  </svg>
</div>

Is it good to do so?

CodePudding user response:

The id attribute's purpose is to give a unique identifier to an element, so that it can be referenced directly in various ways. Using duplicate values violates the HTML and SVG standards, and is likely to lead to problems.

The WHATWG HTML/DOM Standard states this clearly:

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 W3C SVG Specification uses the term "unique name", and references the XML Specification:

Standard XML attribute for assigning a unique name to an element. Refer to the Extensible Markup Language (XML) 1.0 Recommendation [XML10].

The XML Specification in turn formalises that uniqueness in these terms:

Values of type ID MUST match the Name production. A name MUST NOT appear more than once in an XML document as a value of this type; i.e., ID values MUST uniquely identify the elements which bear them.

In practice, browsers are very tolerant of invalid markup, so you won't just get an error on the screen if you actually define duplicates. However, using that ID value for anything will be difficult - CSS selectors, JavaScript DOM APIs, and URL fragments may behave inconsistently from each other and between browsers.

CodePudding user response:

Strictly speaking not invalid.

Duplicate IDs (once, 20 to 15 years ago) had a meaning when IE was the dominant browser,
and all browsers since have copied IE behavior:

  • IDs become global variables referencing the DOM Element (and still do in all browsers)

  • Duplicate IDs return(ed) an Array(nodeList) of all Elements (Firefox no longer does nowadays)

See what your browser does:

console.log("Global variable 'main' is:",typeof main,main.length,"elements");
<div id="main">
  <svg>
      <defs> 
        <circle id="main"/>
      </defs>
      <path id="main" />
  </svg>
</div>

In general duplicate IDs are considered bad practice.
And they do break using SVG patterns, clips etc. where ID references are crucial.

In modern browsers you can use shadowDOM to encapsulate HTML (and CSS).
That allows for using the same (not duplicates anymore) IDs

  • Related