Skip to content Skip to site navigation

When Working with Element IDs, Make Them Unique

Tuesday, November 9, 2021

Under accessibility checks, you may have an issue labeled "Element IDs are not unique" highlighted on your website. This is a fairly common issue across Stanford sites (and many others outside of Stanford too) and it's a bit of a technical issue, so some background information might be helpful. You may need some help from your web developer or other IT professional to make the necessary corrections.

Take the following code for example:

<h1 id="ArticleTitle">This is the title</h1>

This by itself is a perfectly compliant use of the ID attribute. According to the HTML specification, the ID value must be valid and unique per page. To be valid in the current HTML5 specification there are very few rules (unlike previous versions of HTML) and now the biggest thing to look out for is making sure there are no spaces. Otherwise, stick to letters, numbers, and most punctuation and you will be fine. Now let's take that same H1 and extend it out a bit:

<article aria-labelledby="articleTitle">
<h1 id="articleTitle">This is the first article</h1>
</article>
<article aria-labelledby="articleTitle">
<h1 id="articleTitle">This is the first article</h1>
</article>

This is a common type of pattern where you have a heading element (H1) with an ID value (as shown in the first example) which is then referenced by the article element, in this case using an aria-labelledby. In this case, however, there are two headings with the same ID value and then two different article elements that reference those. This creates an accessibility barrier as assistive technology such as screen readers use that value to associate the article and the heading with each other.

So, what would happen with the above code if a user of assistive technology were to encounter it? No one knows without testing. Some AT may read it correctly, some may read every single H1 for every single article, others may read just the first H1 for every article. How AT deals with bad code can be a bit of a mystery (they have a hard enough time getting good code to be read correctly, let alone bad code). 

In addition, this is just plain bad HTML. Other technologies, such as search bots, may also have trouble reading your content with this type of error in your code. Therefore, even if that ID is never referenced it still must be unique on the page. So, watch out for this error and make sure all your ID values are valid and unique.

<article aria-labelledby="articleTitle1">
<h1 id="articleTitle">This is the first article</h1>
</article>
<article aria-labelledby="articleTitle2">
<h1 id="articleTitle">This is the first article</h1>
</article>

DISCLAIMER: UIT Blog is accurate on the publication date. We do not update information in past blog entries. We do make every effort to keep our service information pages up-to-date. Please search our service pages at uit.stanford.edu/search.