HTML Id



The id attribute refers to a unique value for an HTML element. This HTML id value can be used with CSS and JavaScript to perform a certain task.

Using The id Attribute

 In the Cascading Style sheet (CSS), we can easily select an element with the specific id by using the # symbol followed by id.

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


Syntax :

<tag id="value"> 

Example :

<!DOCTYPE html>
<html>
  <head>
    <title>Example of Id attribute in CSS</title>
    <style>
      #Cats {
        padding: 30px;
        background-color: rgb(230, 210, 173);
        color: black;
        text-align: center;
      }

      #Cows {
        padding: 30px;
        background-color: rgb(216, 144, 238);
        text-align: center;
      }
    </style>
  </head>
  <body>
    <h1>Use CSS to style an element with the id:</h1>
    <h1 id="Cats">Cats</h1>
    <h1 id="Cows">Cows</h1>
  </body>
</html>

Output :


HTML id with JavaScript


Example :

<!DOCTYPE html>
<html>
  <body>
    <h2>HTML id with JavaScript</h2>
    <h1 id="hello">Hello Friends!!!</h1>
    <button onclick="displayResult()">Change text</button>
    <script>
      function displayResult() {
        document.getElementById("hello").innerHTML = "All the best for future!";
      }
    </script>
  </body>
</html>

Output :


Difference between HTML Class and ID

An HTML class name can be used by multiple elements while An HTML element can only have one unique id that belongs to that single element.