<htmlstart/>

HTML Id

The id attribute gives an element a unique identifier used by CSS and JavaScript.

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

idclass
UniquenessMust be uniqueReusable on many elements
CSS selector#name.name
Best forOne unique element, JS hooks, anchorsStyling groups of elements
Prefer classes for styling. Use ids for JavaScript targets, form label bindings, and page anchors.