HTML 'id' Attribute

πŸ” What is the id Attribute in HTML?

The id attribute is a unique identifier used to target a specific HTML element. Unlike class, which can be reused, an id must be unique within the page.

>>β€œUse id when you need a name tag on your HTML element β€” one that no other element shares.” 🏷️

πŸ“Œ Syntax

Basic id Example

<h1 id="main-title">Welcome</h1>

This assigns an ID of main-title to the <h1> element.

🎨 Styling with CSS

In CSS, you use the # symbol to target an element by its id.

CSS using id selector

#main-title {
  color: crimson;
  font-size: 2rem;
}

This will style only the element with id="main-title".

βš™οΈ Using id in JavaScript

JavaScript commonly uses the id attribute to quickly access an element.

JavaScript targeting an id

const title = document.getElementById("main-title");
title.textContent = "Updated Title";

🚫 id vs class

Aspectidclass
UniquenessMust be uniqueCan be reused
CSS Selector#id.class
UsageSpecific elementGroup of elements

πŸ’‘ When to Use id

  • 🎯 When targeting a single, specific element
  • πŸ“ For anchor links and bookmarks (e.g., <a href="#section">)
  • πŸ“œ To uniquely reference an element with JavaScript

Note

⚠️ Avoid assigning the same id to multiple elements. It can cause bugs in both CSS and JavaScript!

πŸ”— Useful Resources

>>β€œEvery HTML element can have a name, but only one can have your unique id.” πŸ’Ž