HTML Id

What is Id in HTML?

HTML Id used to specify a unique id for an HTML element.

You cannot have more than one element with the same id in an HTML document.


HTML Id example:

                            
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HTML id Example</title>
  <style>
    #content-container p{
        color: red;
    }
  </style>
</head>
<body>
  <h1 id="main-heading">Heading 1</h1>

  <div id="content-container">
    <p>This is a paragraph inside a div with the id "content-container".</p>
  </div>
</body>
</html>
                            
                          

The id attribute can also be used by JavaScript

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

Example

                            
                              <script>
                                function displayResult() {
                                  document.getElementById("header").innerHTML = "Hello!";
                                }
                              </script>