The id
attribute in HTML is used to uniquely identify an element within a page. Each id
must be unique within a document, meaning no two elements should have the same id
.
To define an id
in HTML, use the id
attribute. You can then reference the id
in your CSS, JavaScript, or when linking within the same page. Here’s an example:
<div id="highlighted-box">
This box is uniquely identified by its ID.
</div>
In your CSS, you can style elements by referencing their id
with a hash symbol (#
) followed by the id
name. For example:
#highlighted-box {
background-color: #f39c12;
padding: 10px;
color: white;
border-radius: 5px;
}
The above CSS code applies a yellow-orange background, padding, white text color, and rounded corners to the element with the id
highlighted-box
.
JavaScript can interact with elements by their id
to dynamically manipulate their content, style, or behavior. For example:
<button onclick="changeContent()">Change Content</button>
<div id="dynamic-content" class="highlight-box">
This content can change.
</div>
<script>
function changeContent() {
document.getElementById("dynamic-content").innerHTML = "Content has been changed!";
}
</script>
You can create links that navigate directly to an element with a specific id
. This is particularly useful for creating a table of contents or navigating long pages. For example:
<a href="#highlighted-box">Go to Highlighted Box</a>