HTML IDs

What Is an ID?

The id attribute uniquely identifies an element on a web page. No two elements should have the same ID in one HTML document — it’s meant for a single, specific element. IDs are often used for direct styling, JavaScript targeting, form label connections, and navigation anchors. Think of an ID as the unique "serial number" of that element.

<div id="main-content">Welcome to the site!</div>

In this example, main-content is the unique ID for the <div> element, which can be referenced in both CSS and JavaScript.

ID Syntax

To assign an ID to an element, use the id attribute with a value of your choice:id="value". The value should be descriptive and meaningful so you can easily remember what the ID represents. IDs must start with a letter (A–Z or a–z) and can contain letters, digits, hyphens (-), underscores (_), and periods (.), but should not contain spaces.

<h2 id="about">About Us</h2>

Here, about is the ID that could be used in CSS for styling or in JavaScript for interaction.

Styling IDs with CSS

In CSS, IDs are targeted using the # symbol followed by the ID name. Since IDs should be unique, styling an ID usually affects only one element on the page.

#about {
  color: darkgreen;
  font-size: 24px;
}

This CSS rule changes the text color of the element with the about ID to dark green and sets its font size to 24 pixels.

Accessing IDs with JavaScript

JavaScript can quickly select an element by its ID using document.getElementById(). This method returns the element object so you can modify its properties, apply styles, or add interactivity.

const element = document.getElementById("main-content");
element.style.backgroundColor = "lightblue";

In this example, the element with ID main-content will have its background color changed to light blue.

IDs and Anchor Links

IDs can be used as link targets within the same page. By creating an anchor link with href="#id", clicking it will automatically scroll to the element with that ID.

<a href="#about">Go to About Section</a>

When clicked, this link scrolls directly to the element with the ID about. This is commonly used for "jump to section" navigation in long pages or table of contents links.

Practice Prompt

Create two sections with IDs: "intro" and "details". Add a link at the top of the page that jumps to the "details" section and use CSS to style it with padding and a background color.

<a href="#details">Skip to Details</a>

<section id="intro">
  <h2>Introduction</h2>
  <p>This is the intro section.</p>
</section>

<section id="details">
  <h2>Details</h2>
  <p>This is the detailed content.</p>
</section>

<style>
  #details {
    background-color: #f0f0f0;
    padding: 20px;
  }
</style>

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic