The HTML id
attribute is used to specify a unique id for an HTML element. which must be unique in the whole document. It allocates the unique identifier which is used by the CSS and the JavaScript for performing certain tasks.
- The
id
value must be unique on the entire HTML document.
- The id can also be used for CSS styling and Javascript Manipulations.
- We can easily select an element with the specific id by using the # symbol followed by id.
Now we can perform some tasks by using ID attribute so that you understand in easy way.
Example
<!DOCTYPE html>
<html>
<head>
<style>
#person {
background-color: purple;
color: white;
border: 5px solid black;
margin: 20px;
padding: 20px;
}
#city{
background-color: red;
color: white;
border: 5px solid black;
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>
<div id ="person">
<h2>Shiva Singam</h2>
<p>Software Engineer</p>
</div>
<div class="city">
<h2>Hyderabad</h2>
<p>Doctor's Colony</p>
</div>
</body>
</html>
Output
Example 2
Now we try another example using ID and Class
<!DOCTYPE html>
<html>
<head>
<style>
#person {
background-color: green;
color: white;
border: 5px solid black;
margin: 20px;
padding: 20px;
}
.city{
background-color: blue;
color: white;
border: 5px solid yellow;
margin: 20px;
padding: 20px;
}
</style>
</head>
<body>
<div id = "person">
<h2>Shiva Singam</h2>
<p>Software Engineer</p>
</div>
<div class = "city">
<h2>Hyderabad</h2>
<p>Doctor's Colony</p>
</div>
</body>
</html>
Output
In the above example we have used id ( #person)
and class name ( .city) to access the HTML element.
Example 3
The id Attribute in JavaScript
We can use the id attribute in javascript to manipulate the HTML elements.
<!DOCTYPE html>
<html>
<head>
<title> Date Attribute </title>
<script>
function viewdate() {
var my_time = new Date();
document.getElementById('demo').innerHTML = my_time
}
</script>
</head>
<body>
<button onclick="viewdate()"> Display Date</button>
<br>
<h2 id="demo"> </h2>
</body>
</html>
Output
- HTML
id
attribute is used to specify a unique id for an HTML element. - The
id
value must be unique on the entire HTML document. - The id can also be used for CSS styling and Javascript Manipulations.