Skip to content

HTML Duplicate ID Attribute

Quick summary

You used id="header" on two elements — getElementById returns the first and styling may apply to the wrong one.

Why this happens

  • Copy-paste error that duplicated an id

  • Template loop that renders the same id for each item

  • Merging components that both use a common id

Minimal example

✗ Broken code
<div id="header">A</div>
<div id="header">B</div>
<script>document.getElementById('header').textContent; // 'A' only</script>
✓ Fixed code
<div class="header" id="header-a">A</div>
<div class="header" id="header-b">B</div>

Two elements share id="header", so getElementById returns only the first. Using class for the shared style and unique ids per element fixes the ambiguity.

How to diagnose

  • Search the HTML for repeated id values

  • Run the W3C validator which reports duplicate IDs

  • Check getElementById results against the expected element

How to fix

  • Use class instead of id for repeated elements

  • Make ids unique by appending an index or key

  • Use data attributes for element identification in lists

How to prevent

  • Reserve id for truly unique elements; use class for repeatable ones

  • Lint HTML for duplicate ids in the build

Related Resources

Related Glossary

Related Lessons

  • HTML

    Learn about IDs and classes.

← Back to language