A webpage is not always broken because of a large mistake. Small details can produce exactly this problem: debugging: duplicate id collision. This guide shows you what to look for, a concrete fix, and how to check that it worked.
The Idea in Plain English
An ID should identify one element in a document. Duplicate IDs break predictable label associations and fragment targets.
You can test this using a small local HTML file. Change one part at a time and check the result in the browser before adding more code.
A Working Example
The first part shows a problem. The second part shows a safer or more accurate version. Compare them before reading the explanation.
<!-- Problem -->
<label for="name">Name</label>
<input id="name">
<input id="name">
<!-- Corrected example -->
<label for="first-name">First name</label>
<input id="first-name" name="first_name">
<label for="last-name">Last name</label>
<input id="last-name" name="last_name">
What Each Part Does
- The label tells visitors and assistive tools what a control is for.
- The input creates a field; its type changes the editing controls and the name identifies submitted data.
- id names an element for labels, fragments, CSS or JavaScript; IDs should be unique.
- for connects a visible label to the control with the same ID.
- name identifies a field in submitted form data or a named metadata entry.
Before the fix, the browser can behave incorrectly or report a warning. After the change, test the exact failure rather than assuming the page is fixed.
Try It Yourself
Search the DOM for each id and confirm it occurs only once.
Common Beginner Mistakes
- Check the underlying cause before changing unrelated tags.
- Changing several parts of the example at once, making it difficult to see which part caused a different result.
- Choosing a tag only because its default appearance looks right, without checking whether it describes the content correctly.
Key Takeaways
- An ID should identify one element in a document. Duplicate IDs break predictable label associations and fragment targets.
- Before the fix, the browser can behave incorrectly or report a warning. After the change, test the exact failure rather than assuming the page is fixed.
- Test the markup in a browser, and check accessibility and real-world behavior where relevant.