HTML ID Attribute

Written by

Aayushi Bansal

HTML id attribute is used to uniquely identify every HTML element from other elements on that page.

Id attribute is known as a global attribute because it can be used on any element.

It is important to note that the value of id attribute of each element should be unique i.e. no two elements on the same page have the same value of their id attributes.

 Having a unique id which identifies each element uniquely, we are able to style our webpage using CSS. The element with a specific id in CSS is selected by using # symbol followed by the name of the id attribute.

For example:

<html>

<head>

<style> #body {   background-color: yellow;   color: black;   padding: 30px;   text-align: left; } </style>

</head>

<body> <h1 id="body">body title</h1>

</body>

</html>

Here the CSS is used on id=”body”

Note: It is important to note that the id is case sensitive which means the value of id attribute i.e. body (used in this example) will be different from Body or BODY. 

Id attribute is also used in JavaScript that allows the script to work with a particular element. Javascript can access an element with a specific id using the getElementById() method.

For example:

<script>
function display() {
  document.getElementById("body").innerHTML = "Good afternoon!";
}
</script>

 

Note: There is another attribute called class which is very similar to the id attribute but the difference lies in the fact that the id for each HTML element should be unique whereas a single class name can be used by multiple HTML elements.

We will learn more about the HTML class attribute in the next chapter.

HTML ID Attribute