slop audit
Blog post 80 / Accessibility and visual design

Duplicate HTML IDs: find and fix broken references

Find duplicate HTML IDs in the rendered DOM, repair form labels, ARIA references, and anchor links, then add a focused Playwright regression test.

By Slop Audit · 6 min read

Duplicate HTML IDs can make a label focus the wrong input, an error message describe the wrong field, or a jump link land in the wrong section. Find collisions in the rendered page, give each target its own ID, and verify that every label, ARIA attribute, and link still points where you expect.

How duplicate HTML IDs break form labels

The HTML standard requires an ID to be unique within its element tree. In a regular page, two elements with id="email" collide even if they sit in separate forms or one is hidden with CSS. Separate pages and iframe documents have separate trees. HTML standard for the id attribute.

Suppose a billing form and a receipt form reuse the same field markup:

<label for="email">Billing email</label>
<input id="email" name="billing_email" type="email">

<label for="email">Receipt email</label>
<input id="email" name="receipt_email" type="email">

Both labels resolve to the first input. In a desktop browser, clicking Receipt email can focus the billing field while the receipt field has no associated label. If the first matching element is a plain div, the browser leaves the label without a control. The label lookup uses the first match in tree order and checks whether that element is labelable. HTML label association rules.

The same collision can affect an aria-describedby hint or an aria-labelledby tab panel. Inspect the actual name and description in the browser's Accessibility panel. A field may have a description that belongs to a different field, even when the markup contains a description attribute. For names supplied through ID references, see the accessible name testing guide. W3C guidance on accessible names and descriptions.

A validator can flag a duplicate as an HTML error. For a WCAG 2.2 review, record the behavior it causes, such as an unnamed input. WCAG 2.2 removed the old Parsing criterion. W3C explanation of the removed Parsing criterion.

Find duplicate HTML IDs in DevTools

Open the deployed route and reproduce the state that fails. If the problem only appears after opening a modal, adding another address, or switching from desktop to mobile, trigger that state first. Run this in the browser console to group elements in the main document by their exact ID value:

const elementsById = new Map();

for (const element of document.querySelectorAll('[id]')) {
  const matches = elementsById.get(element.id) ?? [];
  matches.push(element);
  elementsById.set(element.id, matches);
}

for (const [id, elements] of elementsById) {
  if (elements.length > 1) {
    console.log(id, elements);
  }
}

Expand each logged array to inspect the elements and their ancestors. In the form example, run document.querySelectorAll('label[for="email"]')[1].control to inspect the exact input associated with the second label. For an anchor, load the full URL with the fragment and see which section the browser targets. The HTML fragment algorithm selects the first element in tree order with the matching ID. HTML fragment navigation algorithm.

If the console finds a collision only after the page hydrates, look for a client-rendered component, a portal, or a second copy mounted at a breakpoint. Check the initial HTML too if the page comes from a shared template or CMS. A CSS-hidden mobile menu still participates in ID lookup. The console snippet covers the main document's light DOM. Switch DevTools to the relevant frame or inspect an open shadow root separately when the affected markup lives there.

Give every target its own ID

In a template, use a readable prefix that identifies the form, section, or record. Update the target and every reference in the same change. Here the two labels each get their own field, and the receipt field gets its own hint.

<label for="billing-email">Billing email</label>
<input id="billing-email" name="billing_email" type="email">

<label for="receipt-email">Receipt email</label>
<input
  id="receipt-email"
  name="receipt_email"
  type="email"
  aria-describedby="receipt-email-hint"
>
<p id="receipt-email-hint">We send receipts to this address.</p>

Keep the form's name values when the backend already expects them. Search the source for the old ID before shipping. Update references such as for, aria-labelledby, aria-describedby, aria-controls, fragment links, and JavaScript lookups. If the ID was only a styling hook, use a class shared by the instances. Keep an existing public fragment on its intended heading so saved links still work. For related panel relationships, see the accessible tabs markup and tests.

Generate IDs for repeated React components

When a component can appear more than once, generate the IDs inside the component. Each instance uses one base ID for its input and derives a second one for its hint.

import { useId } from 'react';

export function EmailField({ label, name, hint }) {
  const inputId = useId();
  const hintId = `${inputId}-hint`;

  return (
    <div>
      <label htmlFor={inputId}>{label}</label>
      <input
        id={inputId}
        name={name}
        type="email"
        aria-describedby={hintId}
      />
      <p id={hintId}>{hint}</p>
    </div>
  );
}

Call useId at the top level of the component. Use data keys when rendering a list of fields. For separate React roots on the same page, configure different identifierPrefix values. In a server-rendered root, use the same prefix on the server and client and keep the component tree consistent during hydration. Use an explicit, stable ID when the target is a public anchor. React useId documentation.

Add a duplicate ID regression test

Exercise a route with both fields present. In this example, set PREVIEW_URL to the full deployed URL for the two-field form. Adjust the selectors and expected description to match your page. For a conditional form, open the section that mounts the second copy before taking the ID inventory.

import { expect, test } from '@playwright/test';

test('billing and receipt fields keep their own labels and IDs', async ({ page }) => {
  const url = process.env.PREVIEW_URL;
  if (!url) throw new Error('Set PREVIEW_URL to the form page.');

  await page.goto(url);

  const billing = page.locator('input[name="billing_email"]');
  const receipt = page.locator('input[name="receipt_email"]');

  await expect(billing).toHaveAccessibleName('Billing email');
  await expect(receipt).toHaveAccessibleName('Receipt email');
  await expect(receipt).toHaveAccessibleDescription(
    'We send receipts to this address.',
  );

  await page.locator('label').filter({ hasText: /^Receipt email$/ }).click();
  await expect(receipt).toBeFocused();

  const duplicates = await page.evaluate(() => {
    const seen = new Set<string>();
    const repeated = new Set<string>();

    for (const element of document.querySelectorAll('[id]')) {
      if (seen.has(element.id)) repeated.add(element.id);
      seen.add(element.id);
    }

    return [...repeated].sort();
  });

  expect(duplicates, 'Repeated IDs in the main document').toEqual([]);
});

The name and description assertions catch incorrect wiring even when every ID is unique. The ID inventory catches other repeated targets in the state the test reached. Run it after opening any conditional UI you need to cover and in both desktop and mobile projects if the layouts mount different markup. For a public jump link, check that the expected heading is the :target after navigating. Then use the website form testing checklist to cover errors and submission outcomes. Playwright assertions reference.

Review the deployed page after the fix

Run Slop Audit on the public form URL after fixing the IDs. When browser evidence is available, review the axe findings and sampled form-label checks for related issues, using the reported selectors where available. Rescan the same URL after addressing those findings. Keep the rendered ID inventory and the exact label and anchor assertions in your own website regression tests so they cover the states your users reach.