HTML Attribute ID - Example

HTML Attribute id can be used on HTML elements, which can be used to apply CSS styles and apply Javascript actions on specific elements.

Here is the example code, where we have tried to apply both Styles and Javascript actions as mentioned below.

  • Applied CSS styles to the heading element <h2> containing ID id="head", which applies a gray background color to the element upon page load.
    • HTML element with an id attribute (value id="head") must be selected using the id with a prefix # (like #head) inside the CSS.
  • Applied JavaScript actions on the same heading element using the ID, which highlights the text in red when the action is invoked.
    • HTML element with an id attribute (value id="head") can be selected using the method getElementById("head") inside the JavaScript.

Run this on IDE

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        #head {
            background-color: gray;
        }
    </style>
</head>
<body>
    <h1>HTML ID Attribute</h1>
    <button onclick="highlightHeading()">Highlight Heading</button>
    
    <h2 id="head">Heading One</h2>
    <p id="para">Paragraph One text goes here.</p>
    <div id="section">
        <h3>Heading</h3>
        <p>Paragraph text within the div</p>
    </div>

    <script>
        function highlightHeading() {
            var x = document.getElementById("head");
            x.style.color = "red";
        }
    </script>
</body>
</html>

Overall

This example helps us understand the use cases of the HTML id attribute.