Using the HTML `id` Attribute for Unique Element Targeting

Learn how to effectively use the HTML `id` attribute to assign unique identifiers to elements for precise styling with CSS and manipulation with JavaScript. This tutorial covers best practices, including naming conventions and important considerations for creating well-structured and accessible web pages.



Using the HTML `id` Attribute

What is the `id` Attribute?

The id attribute assigns a unique identifier to an HTML element. No two elements on a single page can share the same id value. This identifier is used by CSS and JavaScript to target and manipulate specific elements.

Using `id` with CSS

The id attribute is used to select a specific HTML element for styling with CSS. You select the element using a hash symbol (#) followed by the id value (e.g., #myHeader).

Example:

HTML

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

#myHeader {
  color: blue;
}

This styles the <h1> element with the id "myHeader" to have blue text.

Important notes: id names are case-sensitive, must contain at least one character, cannot start with a number, and cannot contain spaces.

`id` vs. `class`

The key difference between id and class is that an id must be unique on a page, while a class can be used by multiple elements.

Example:

HTML

<h1 class="city">London</h1>
<h1 class="city">Paris</h1>
<h1 id="tokyo">Tokyo</h1>

HTML Bookmarks with `id`

The id attribute is also used to create bookmarks within a page. You create a bookmark using the id attribute on an element, then link to it using href="#id_value".

Example:

HTML

<h2 id="chapter4">Chapter 4</h2>
<a href="#chapter4">Jump to Chapter 4</a>

Using `id` with JavaScript

JavaScript's getElementById() method accesses an element by its id. This allows you to manipulate the element using JavaScript.

Example:

JavaScript

document.getElementById("myElement").innerHTML = "New text!";