jQuery and Multiple Elements With the Same ID: Why It Fails and How to Fix It

Duplicate IDs are invalid HTML, so $("#red") stops at the first match. An attribute selector finds them all, but the real fix is to use classes.

$('#red') returns only the first element with id="red", because IDs must be unique and browsers stop at the first match. To select every element with a repeated ID, use an attribute selector: $('[id="red"]') or document.querySelectorAll('[id="red"]'). That works as a stopgap, but the proper fix is to change the duplicates to a class, such as class="red", and select them with $('.red').

Originally published in August 2013. Rewritten in December 2026 to recommend fixing the markup.

Why only the first one is found

The HTML standard says an id must be unique in the document. Browsers look up #red with a fast ID index, which returns a single element. jQuery uses the same lookup, so it never sees the others.

The workaround

$('[id="red"]').addClass('bg-red');
$('[id="green"]').addClass('bg-green');
document.querySelectorAll('[id="red"]').forEach((el) => el.classList.add('bg-red'));

Attribute selectors don’t use the ID index, so they return every match. They’re slower than ID or class lookups, though rarely enough to matter.

The fix: use classes or data attributes

<div class="swatch red">…</div>
<div class="swatch green">…</div>
<div class="swatch red">…</div>
$('.swatch.red').addClass('bg-red');

For elements you need to tell apart in JavaScript, a data attribute is often clearer than a class:

<button data-product-id="42">Add to cart</button>
$(document).on('click', '[data-product-id]', function () {
  const id = $(this).data('productId');
});

Duplicate IDs cause other bugs

Fixing them is worth it even if your selector works:

  • <label for="email"> points to the first field with that ID, so clicking the second label focuses the wrong input.
  • aria-labelledby and aria-describedby connect to the wrong elements, which confuses screen reader users.
  • Links to #section jump to the first match only.
  • Form libraries and frameworks that look elements up by ID behave unpredictably.

Duplicate IDs often come from repeating a template in a loop. Add the item’s own ID to make them unique, such as id="qty-<?= $item->id ?>".

Find duplicates on a page

Run this in the browser console:

const seen = {};
document.querySelectorAll('[id]').forEach((el) => {
  seen[el.id] = (seen[el.id] || 0) + 1;
});
console.table(Object.entries(seen).filter(([, n]) => n > 1));

The W3C HTML validator and Lighthouse’s accessibility audit also report duplicate IDs.

Common questions

Does getElementById return all matches?

No. It returns one element, the first in the document.

Will duplicate IDs break my site?

The page will render, but scripts, labels and accessibility features can quietly misbehave.

Can I use the same ID on different pages?

Yes. IDs only need to be unique within one page.