HTML 'id' Attribute
π What is the id Attribute in HTML?
The id attribute is a unique identifier used to target a specific HTML element. Unlike class, which can be reused, an id must be unique within the page.
>>βUse id when you need a name tag on your HTML element β one that no other element shares.β π·οΈ
π Syntax
Basic id Example
<h1 id="main-title">Welcome</h1>This assigns an ID of main-title to the <h1> element.
π¨ Styling with CSS
In CSS, you use the # symbol to target an element by its id.
CSS using id selector
#main-title {
color: crimson;
font-size: 2rem;
}This will style only the element with id="main-title".
βοΈ Using id in JavaScript
JavaScript commonly uses the id attribute to quickly access an element.
JavaScript targeting an id
const title = document.getElementById("main-title");
title.textContent = "Updated Title";π« id vs class
| Aspect | id | class |
|---|---|---|
| Uniqueness | Must be unique | Can be reused |
| CSS Selector | #id | .class |
| Usage | Specific element | Group of elements |
π‘ When to Use id
- π― When targeting a single, specific element
- π For anchor links and bookmarks (e.g., <a href="#section">)
- π To uniquely reference an element with JavaScript
Note
β οΈ Avoid assigning the same id to multiple elements. It can cause bugs in both CSS and JavaScript!
π Useful Resources
>>βEvery HTML element can have a name, but only one can have your unique id.β π