id Attribute: id Attribute?✔ The id attribute uniquely identifies an HTML element.
✔ Unlike class, an id must be unique within a page (no two elements should have the same id).
✔ It is mainly used for styling (CSS), JavaScript manipulation, and linking to sections.
id<tag id="unique-id">Content</tag>
✔ The id is assigned to an element for styling or interactivity.
id in CSS<!DOCTYPE html>
<html lang="en">
<head>
<style>
#heading {
color: blue;
font-size: 24px;
text-align: center;
}
</style>
</head>
<body>
<h2 id="heading">This is a unique heading</h2>
</body>
</html>
✔ The id="heading" targets this specific <h2> element in CSS.
id in JavaScriptThe id attribute allows JavaScript to access and manipulate an element easily.
<!DOCTYPE html>
<html lang="en">
<head>
<script>
function changeText() {
document.getElementById("message").innerHTML = "Text changed!";
}
</script>
</head>
<body>
<p id="message">Click the button to change this text.</p>
<button onclick="changeText()">Click Me</button>
</body>
</html>
✔ Clicking the button modifies the text inside the <p> with id="message".
id for Internal Page LinksYou can use id to create jump links within a page.
<a href="#section2">Go to Section 2</a>
<h2 id="section2">Section 2</h2>
<p>This is the second section.</p>
✔ Clicking the link scrolls the page to the id="section2" section.
id and class| Feature | id (id="...") |
class (class="...") |
|---|---|---|
| Uniqueness | Must be unique (one per page) | Can be used multiple times |
| Syntax | id="header" |
class="box" |
| Used in CSS | #header {} |
.box {} |
| Used in JavaScript | document.getElementById("header") |
document.getElementsByClassName("box") |
✔ Use id for unique elements (like header, footer, or buttons).
✔ Use class for reusable styles (like buttons, cards, sections).
id✅ Use id only for unique elements (e.g., id="navbar", id="footer").
✅ Avoid using id for styling—prefer class for better maintainability.
✅ Use id in JavaScript for selecting and modifying elements.
✅ Follow meaningful naming conventions (id="main-content", not id="123").