In one of the previous posts, we were talking about the HTML class attribute which defines equal styles of elements, today we’ll focus on the second very important attribute which defines HTML element – HTML id.

The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document). The id attribute can be used on any HTML element.
The id value can be used by CSS and JavaScript to perform certain tasks for the element with the specific id value.
In CSS, to select an element with a specific id, use a hash (#) character, followed by the id of the element:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
#header {
background-color: #2a9d8f;
color: white;
padding: 40px;
text-align: center;
}
</style>
</head>
<body>
<h4 id="header">Header</h4>
</body>
</html>
Output:
Header
Difference Between Class and ID:
An HTML element can only have one unique id that belongs to that single element, while a class name can be used by multiple elements:
<!DOCTYPE html>
<html>
<head>
<style>
#header {
background-color: #2a9d8f;
color: white;
padding: 40px;
text-align: center;
}
.city {
background-color: #e9c46a;
color: #264653;
padding: 10px;
}
</style>
</head>
<body>
<h3 id="header">The Capitals:</h3>
<h4 class="city">London</h4>
<p>London is the capital of the United Kingdom.</p>
<h4 class="city">Brussels</h4>
<p>Brussels is the capital of Belgium.</p>
<h4 class="city">Bangkok</h4>
<p>Bangkok is the capital of Thailand.</p>
</body>
</html>
Output:
The Capitals:
London
London is the capital of the United Kingdom.
Brussels
Brussels is the capital of Belgium.
Bangkok
Bangkok is the capital of Thailand.
Using The id Attribute in JavaScript:
JavaScript can access an element with a specified id by using the getElementById() method (you can read more about this method here):
<!DOCTYPE html>
<html>
<body>
<h4 id="header">Hello!</h4>
<button onclick="displayResult()">Change text</button>
<script>
function displayResult() {
document.getElementById("header").innerHTML = "Have a nice day!";
}
</script>
</body>
</html>
Output:
Hello!
Enjoy coding!
Read also: