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.
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>
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.
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>
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!";
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>
Avoid spaces and special characters when naming ids. Use lowercase letters, hyphens, or camelCase format, e.g., main-title or contactSection.
Select Language
Set theme
© 2025 ReadyTools. All rights reserved.