An id must be unique within a live document. Duplicate IDs produce unpredictable querySelector results and break accessibility mappings.
Primary uses
- Fragment identifiers in URLs (
#pricing). <label for="email">referencing<input id="email">.- ARIA relationships (
aria-labelledby,aria-controls). - Stable anchors for scripts when necessary.
Contrast with classes
- IDs have extreme specificity in CSS—avoid styling via IDs unless unavoidable.
- Classes scale for repeating patterns; IDs designate singletons.
Dynamic apps
Server-rendered duplicates happen when lists reuse IDs inside loops—switch to classes or generate stable unique IDs per row (keys in React reconciliation are not IDs in the DOM).
Why duplicate IDs haunt production
- First match wins APIs—analytics or tests attach to wrong node silently.
- Browser extension password managers autocomplete into wrong inputs when duplicated fields share IDs.
Fragment link + target id
<a href="#notes-section">Jump to notes</a>
…
<h2 id="notes-section">Notes</h2>
Rendered — click to scroll inside this lesson
Intermediate filler so the jump is noticeable…
…
Demo target (id anchor)
Screen readers and search engines use stable ids for deep links.
Important interview questions and answers
- Q: What is the practical difference between `id` and `class`?
A: `id` must be unique and is used for fragments/labeling; `class` is reusable for styling and behavior grouping. - Q: Why is `defer` commonly preferred for scripts?
A: It preserves HTML parsing, executes after parse, and avoids blocking rendering unlike classic synchronous scripts. - Q: How do `srcset` and `sizes` work together?
A: `srcset` provides candidate files and `sizes` tells expected rendered width so the browser can pick an optimal resource.
Pitfall: IDs must be unique per page—use classes for repeated styling.