HTML · Chapter 23 of 45

HTML Id Attribute

The id attribute gives an element a unique identifier within the page — no two elements should share the same id value. IDs are used for CSS styling, JavaScript targeting, and page anchors.

In CSS, an id is targeted using a hash prefix (#idname). Because ids should be unique, they're often used for one-off elements or as JavaScript hooks like document.getElementById().

Syntax
<tagname id="uniqueName">

Uniqueness rule

Unlike classes, an id value must appear only once per page. Using duplicate ids can cause unpredictable CSS and JavaScript behavior.

Id as an anchor

An id can be used as a link target: <a href="#top">Back to top</a> jumps to the element with id="top".

Example 1 (html)
<h2 id="about">About Us</h2>
<style>#about { color: navy; }</style>
Output
About Us (navy colored)

The id targets one specific element with CSS.

Example 2 (html)
<a href="#top">Back to top</a>
...
<h1 id="top">Page Top</h1>
Output
Back to top (jumps to Page Top)

Clicking the link scrolls the page to the element with matching id.

Key points

  • id must be unique per page.
  • CSS targets an id with a hash: #idname.
  • JavaScript often uses getElementById() to find elements.
  • ids can serve as jump-to anchors within a page.
💡 Note: Prefer classes for reusable styling and reserve ids for unique, single-use elements.

📝 Quick Quiz

1. How many elements on a page can share the same id?

2. How do you target an id in CSS?

3. Which JS method commonly finds an element by id?