In HTML, an ID is a unique identifier assigned to a single element. IDs help you target specific elements using CSS, JavaScript, and internal page links.
<p id="intro">This is an introduction paragraph.</p>
To style an element with an ID:
<style>
#intro {
color: blue;
font-size: 20px;
}
</style>
<p id="intro">Styled with an ID selector!</p>
JavaScript can fetch an element using its ID:
<p id="message">Hello</p>
<script>
document.getElementById("message").innerHTML = "Updated using JavaScript!";
</script>
IDs allow 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>
| Rule | Explanation |
|---|---|
| Unique | No two elements can have the same ID |
| One per element | A single element cannot have multiple IDs |
| Case-sensitive | #Header ≠ #header |
| Use letters first | ID names should not start with numbers |
<label for="name">Name:</label>
<input type="text" id="name" name="name">
The for attribute links the label directly to the element with matching ID.