Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 122 Β· Page Structure and Layout

IDs

Give elements unique ids for page jumps, form labels and JavaScript. Learn the rules for valid ids, why to be careful with id selectors in CSS, and getElementById.

A class puts elements into groups. An id does the opposite: it gives one element a name that no other element on the page shares. Like a street address, it lets you point to exactly one place.

That uniqueness is what makes ids useful. Links can jump to them, form labels can connect to them, accessibility attributes can reference them and JavaScript can fetch an element by them in one step. This lesson covers all of these uses, the rules for writing ids, and the one place where ids are best avoided: CSS styling.

The id attribute

id is a global attribute, so any element can have one:

HTML
<section id="opening-hours">
  <h2>Opening hours</h2>
  …
</section>

The rules are short:

  • Unique. No two elements in the same document may have the same id.
  • At least one character, and no whitespace. id="opening hours" is invalid; use opening-hours.
  • Case-sensitive. Menu and menu are two different ids.
  • One per element. Unlike class, an element has a single id, not a list.

Anything else is technically allowed, including ids that start with a digit. But as with classes, ids made of lowercase letters, digits and hyphens, starting with a letter, are the easiest to use in URLs, CSS and JavaScript.

Duplicate ids fail quietly. The browser won't show an error. Instead, links jump to the first match, getElementById returns only the first match, and labels and ARIA references may connect to the wrong element. A validator (see Validating Your HTML) catches duplicates for you.

Jumping to a part of the page

When a URL ends with # and an id, the browser scrolls to the element with that id. This is called a fragment link:

Jump links with fragments

Click a link and the matching section scrolls into view. The CSS :target pseudo-class highlights whichever element is currently named in the URL's fragment, a nice touch that helps people see where they've landed.

Fragments work across pages too: /visit#tickets opens the visit page and jumps to its tickets section. You'll find more about these links in Link Targets and Page Jumps.

Choose stable, readable ids. Once people share or bookmark …/visit#tickets, renaming the id breaks their links. Short, descriptive ids like tickets make better URLs than section-3.

Connecting labels and form controls

A form field needs a visible label, and the label must be tied to its field. The for attribute on <label> holds the id of the control it describes:

HTML
<label for="arrival">Arrival date</label>
<input type="date" id="arrival" name="arrival">

Clicking the label now focuses the field, and screen readers announce "Arrival date" when the field receives focus. This only works if the id is unique; with a duplicate, the label may point to the wrong input. Labels, Fieldsets and Legends covers this in depth.

Accessibility attributes use ids the same way. aria-labelledby and aria-describedby take one or more ids, and the table headers attribute from Accessible Tables does too:

HTML
<input type="password" id="new-pass" aria-describedby="pass-hint">
<p id="pass-hint">At least 12 characters.</p>

Finding an element with JavaScript

document.getElementById() returns the element with that id, or null if there isn't one. Notice there's no # in the argument, just the id itself:

getElementById

querySelector('#counter') finds the same element. That's handy when you're already writing selectors, but there you do need the #, because it's a CSS selector. getElementById is a little faster and reads clearly when all you have is an id.

Ids also become global variables. For historical reasons, browsers expose an element with id="counter" as window.counter. Don't rely on it: a variable or a later element with the same name silently replaces it, and the code becomes hard to follow. Always look elements up explicitly.

Ids in CSS: handle with care

CSS can select by id with #:

CSS
#counter { font-size: 2em; }

This works, but id selectors are very specific. In the cascade, one id outweighs any number of classes. So if you style something with #signup .btn, a later, simpler rule like .btn-danger can't override it without another id or !important. Stylesheets full of ids turn into a battle of ever-stronger selectors.

An id wins over classes

The "urgent" paragraph stays blue even though the red rule comes later. That's specificity at work.

A practical approach:

  • Use classes for styling, almost always.
  • Use ids for things that need a unique name: fragment links, labels, ARIA references and JavaScript lookups.
  • If you must style a uniquely named element, an attribute selector like [id="counter"] matches it with only class-level specificity.

Id or class?

You want to… Use
Style several elements the same way class
Link to a section of a page id
Connect a <label> to an input id (with for)
Reference an element from aria-describedby id
Toggle a state like "open" or "done" with JavaScript class
Fetch one specific element in JavaScript id (or a class with querySelector)

An element may have both, and often does: <nav id="main-menu" class="menu menu--dark">.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Two elements on a page have id="intro". What happens?

    Duplicate ids don't cause visible errors, which is what makes them dangerous. Lookups and fragment links quietly use the first match.
  2. 2. Which link jumps to <section id="faq"> on the same page?

    A fragment starts with # followed by the id. Without the #, the browser looks for a page called faq.
  3. 3. What should you pass to document.getElementById() to find <p id="total">?

    getElementById takes the plain id. The # is only needed in CSS selectors, for example with querySelector('#total').
  4. 4. Why do many developers avoid id selectors in CSS?

    One id outweighs any number of classes, so styles set with ids are hard to change later without even stronger selectors.

Summary

  • An id names exactly one element; it must be unique, contain no whitespace and is case-sensitive.
  • href="#id" jumps to that element, on the same page or another, and :target styles the destination.
  • <label for="id">, aria-labelledby, aria-describedby and table headers all point to elements by id.
  • document.getElementById('id') returns the element or null; no # in the argument.
  • Id selectors are very specific in CSS, so prefer classes for styling and keep ids for links, forms, accessibility and scripts.

Next lesson: Semantic Elements.