The id
attribute in HTML is used to specify a unique identifier for an HTML element. Unlike the class
attribute, which can be used to group similar elements together, the id
attribute should only be used once per page for a specific element.
The id
attribute is commonly used in CSS and JavaScript to target specific elements and apply styles or functionality to them. To use the id
attribute, you simply need to add it to an HTML element with a unique identifier.
For example, let’s say you have a heading element that you want to apply a specific style to using CSS. You could add the id
attribute to the heading like this:
<h1 id="my-heading">My Heading</h1>
Now you can target this element in your CSS stylesheet using the #
symbol followed by the id
value:
#my-heading {
color: red;
}
This will apply a red color to the text of the heading element with the my-heading
ID.
You can also use the id
attribute in JavaScript to manipulate an element. For example, you could use the getElementById()
method to select the element with a specific ID and change its contents:
const myHeading = document.getElementById('my-heading');
myHeading.textContent = 'New Heading Text';
In summary, the id
attribute in HTML is used to provide a unique identifier for an element, which can be used to target it in CSS and JavaScript.