HTML Id

The HTML id attribute uniquely identifies a single element on a page so it can be styled with CSS or accessed with JavaScript. Each id value must be used only once within an HTML document.

On this page

HTML id Attribute

The id attribute is used to assign a unique identifier to an HTML element.

An id value must be unique within the HTML document.

The id Attribute

The id attribute identifies a single element and can be used by CSS and JavaScript.

Unlike classes, an id can only be used once on a page.

<h1 id="myHeader">My Header</h1>

Using id with CSS

In CSS, an id selector is defined using a hash (#) followed by the id name.

#myHeader {   background-color: lightblue;   color: black;   padding: 40px;   text-align: center; }

The style is applied only to the element with the matching id.

Rules for id Values

  • An id must be unique within the document
  • An id must contain at least one character
  • An id cannot start with a number
  • An id must not contain spaces
  • Id values are case sensitive

Difference Between class and id

A class can be used on multiple elements, while an id is used on a single element.

<h1 id="myHeader">My Cities</h1>  <h2 class="city">London</h2> <p class="city">London is the capital of England.</p>

HTML Bookmarks Using id

The id attribute can be used to create bookmarks within a page.

Bookmarks allow users to jump to specific sections of a long page.

<h2 id="C4">Chapter 4</h2>

A link can point to the bookmark using the hash symbol.

<a href="#C4">Jump to Chapter 4</a>

Using id with JavaScript

JavaScript can access an element by its id using getElementById().

document.getElementById("myHeader").innerHTML = "Have a nice day!";

Chapter Summary

  • The id attribute uniquely identifies an element
  • Each id value must be used only once per page
  • Ids are commonly used with CSS and JavaScript
  • The id attribute can create page bookmarks

HTML Attributes

Attribute Description
id Specifies a unique identifier for an element

HTML Id Examples (5)