HTML reference

id

The id attribute gives an element a unique identifier within a document. You can use it for fragment links, CSS selectors, and JavaScript.

What you will learn

  • Why an id must be unique
  • How to use it for links, CSS, and JavaScript
  • How id differs from class

Basic example

<h2 id="features">Features</h2>
<a href="#features">Jump to features</a>

<style>
  #features { color: darkblue; }
</style>

The value must be unique in the document and must not contain spaces. Choose a meaningful name that describes the element, not its current appearance.

id and class

Use id when one specific element needs a stable identity. Use class when the same style or behavior applies to several elements. An element can have both.

JavaScript and accessibility

const heading = document.getElementById("features");

Use an id to connect related controls with attributes such as aria-controls or aria-labelledby. Do not duplicate an identifier, because links and scripts may target the wrong element.

Related pages