Loading...

Using the id Attribute in HTML

The id attribute allows you to assign a unique identifier to an HTML element. It is essential for styling in CSS, manipulation in JavaScript, or for navigation within the page.

What Is the id Attribute?

The id is a unique identifier assigned to an element. An id can only appear once per page. This attribute is usually a short, descriptive name.

html

<h2 id="section1">Introduction</h2>

Importance of Uniqueness

The id attribute can appear only once in a document. This is what sets it apart from the class attribute, which can be used multiple times. If two elements have the same id, it may cause errors in CSS or JavaScript.

Using id in CSS

In CSS, the id attribute is indicated with a # symbol. It allows us to assign styles to a specific element, such as colors, sizes, or layouts.

css

#main-title {
  color: blue;
  font-size: 24px;
}

html

<h1 id="main-title">Welcome to the site</h1>

Using id in JavaScript

In JavaScript, you can access an element by its id using the getElementById method. This allows you to dynamically modify content or style.

javascript

document.getElementById("main-title").innerText = "Hello!";

id in In-Page Navigation

When a link points to an id, the browser will automatically scroll to the corresponding element. This is useful for long pages, such as FAQs or tables of contents.

html

<a href="#contact">Go to contact section</a>

...

<h2 id="contact">Contact Us</h2>

Naming Rules for id

Avoid spaces and special characters when naming ids. Use lowercase letters, hyphens, or camelCase format, e.g., main-title or contactSection.

Track Your Progress 🚀

Learn more easily by tracking your progress completely for free.


Top tools

CodeHubBoardly NEWLinksy NEWChromo NEW

Select Language

Set theme

© 2025 ReadyTools. All rights reserved.