Skip to main content

HTML id Attribute

The id attribute sets a unique id for an HTML element. You cannot have two elements with the same id in one document.


The id Attribute

The id attribute gives an element a unique id, which must be unique in the document. It points to a specific style in a style sheet, and JavaScript uses it to reach and change that element. To write the CSS, use a hash (#) followed by the id name, then the properties in curly braces.

Note: The id name is case sensitive. Note: It must have at least one character, cannot start with a number, and cannot contain spaces.

Example

An <h1> styled by its id.

Prompt
A page with an h1 that has id="myHeader", styled by a #myHeader rule in the head (light blue background, black text, padding, centered).
Output: complete HTML page

Difference Between Class and ID

A class name can be used by many elements, but an id must be used by only one element on the page.

Example

A unique id alongside a shared class.

Prompt
A page showing the difference between id and class: one h1 with a unique id myHeader, and three h2 elements sharing the city class, each styled by its own rule.
Output: complete HTML page

HTML Bookmarks with ID and Links

Bookmarks let readers jump to a specific part of a page, which is handy on a long page. First create the bookmark by giving an element an id, then add a link to it with href="#id". When the link is clicked, the page scrolls to that element. You can also link to a bookmark on another page by putting the file name before the #.

Example

A link that jumps to Chapter 4 on the same page.

Prompt
A long page with a link at the top "Jump to Chapter 4" pointing to #C4, and further down an h2 with id="C4" reading "Chapter 4", with filler content between so clicking scrolls down.
Output: complete HTML page

Bookmark on another page

Linking to a bookmark on a different page.

index.html
<a href="html_demo.html#C4">Jump to Chapter 4</a>

Using the id Attribute in JavaScript

JavaScript can use the id to work with that specific element. The getElementById() method finds the element with a given id.

Example

A button that changes a heading's text with JavaScript.

Prompt
A page with a button that runs JavaScript using getElementById to change the text of an element with id myHeader to "Have a nice day!"
Output: complete HTML page

Chapter Summary

To recap: the id attribute sets a unique id for an element, and the value must be unique in the document. CSS and JavaScript use it to style or select a specific element, the value is case sensitive, and it is also used to make bookmarks. JavaScript can reach the element with getElementById().