The id Attribute
Every id must be unique on a page. Target it in CSS with # and in JavaScript with getElementById().
<!-- HTML -->
<h1 id="page-title">Welcome</h1>
<div id="sidebar">...</div>/* CSS */
#page-title { color: #D62828; font-size: 3rem; }
#sidebar { width: 280px; background: #f5f5f0; }IDs as Page Anchors
Link directly to any element on the page using its id:
<a href="#contact">Jump to contact section</a>
<!-- Further down the page -->
<section id="contact">
<h2>Contact Us</h2>
...
</section>JavaScript Access
const title = document.getElementById("page-title");
title.textContent = "New title!";
title.style.color = "blue";id vs class
| id | class | |
|---|---|---|
| Uniqueness | Must be unique | Reusable on many elements |
| CSS selector | #name | .name |
| Best for | One unique element, JS hooks, anchors | Styling groups of elements |
Prefer classes for styling. Use ids for JavaScript targets, form label bindings, and page anchors.