HTML The id Attribute
Using The id Attribute
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 by CSS and JavaScript to perform certain tasks for a unique element with the specified id value.
To select an element with CSS with a specific id, write a hash (#) character, followed by the id of the element:
Example
Use CSS to style an element with the id "myHeader":
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;} </style>
<h1 id="myHeader">My Header</h1>
Difference Between Class and ID
An HTML page can only have one unique id applied to a specific element, while a class name can be applied to multiple elements:
Example
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;}
.city {
background-color: tomato;
color: white;
padding: 10px;} </style>
<h1 id="myHeader">My Cities</h1>
<h2 class="city">London</h2>
<p>London is the capital of England.</p>
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
Using The id Attribute in JavaScript
JavaScript can access an element with a specified id by using the getElementById() method:
Example
Use the id attribute to manipulate text with JavaScript:
<script>
function displayResult() {
document.getElementById("myHeader").innerHTML = "Have a nice day!";
}
</script>