/    /  HTML Id

HTML Id

 

The HTML id attribute is used to provides the unique ID for an element of the HTML document. It allows the unique identifier which is provided by the CSS and the JavaScript for performing certain tasks.

Note: In the CSS, we can easily select an element with the specific id by using the # symbol followed by id.

Note: JavaScript can access an element with the given ID by using the getElementById() method.

 

Example:

 

<body>
<h1 id="apple"> APPLE</h1>
<h1 id="name"> NAMES</h1>
</body>

Style:

#apple {
padding: 40px;
background-color: blue;
color: black;   
text-align: center;
}

#name
{
padding: 50px;
background-color: Green;
text-align: center;
}

 

OUTPUT:

 

HTML Id

 

Difference Between Class and ID:

 

A class name can be used by various HTML elements, while an id name must only be used by one HTML element within the web page.

 

Example:

 

<h1 id="myHeader">My Cities</h1>
<h2 class="city">Hyderabad</h2>
<h2 class="city">Paris</h2>
<h2 class="city">Tokyo</h2>

 

Styles:

 

#myHeader {
 background-color: lightblue;
 color: black;
 padding: 40px;
 text-align: center;
}

.city {
 background-color: green;
 color: white;
 padding: 10px;
}

 

OUTPUT:

 

HTML Id

 

The id Attribute in JavaScript:

 

JavaScript can access an element with a specific id element with the getElementById() method.

 

Example:

 

<h1 id="myHeader">Hello World!</h1>
<button onclick="displayResult()">Change text</button>
Javascript:
<script>
function displayResult() {
 document.getElementById("myHeader").innerHTML = "Have a nice day!";
}
</script>

 

OUTPUT:

 

HTML Id