HTML Id Attribute

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

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

The value of the id attribute must be unique within the HTML document.

The id name must not contain whitespaces (spaces, tabs, etc.).

The id name is case sensitive.

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.

Difference Between Class and ID

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

HTML Id Attribute – CSS Example

<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
  background-color: lightblue;
  color: black;
  padding: 40px;
  text-align: center;
} 
</style>
</head>
<body>

<h2>The id Attribute</h2>
<p>Use CSS to style an element with the id "myHeader":</p>

<h1 id="myHeader">My Header</h1>

</body>
</html>
HTML Id Attribute – CSS Example Output

HTML Id Attribute – JavaScript Example

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Id Attribute - JavaScript Example</title>
</head>

<body>

    <body>

        <h2>Using The id Attribute in JavaScript</h2>
        <p>JavaScript can access an element with a specified id by using the getElementById() method:</p>

        <h1 id="myHeader">Hello World!</h1>
        <button onclick="displayResult()">Change text</button>

        <script>
            function displayResult() {
                document.getElementById("myHeader").innerHTML = "Have a nice day!";
            }
        </script>

    </body>
</body>

</html>