View video tutorial

HTML id Attribute

HTML

The HTML id attribute is used to specify a unique identifier for a single HTML element within a document.

Definition and Usage


➔ ID must be unique within the same HTML document.

➔ ID names are case-sensitive.

➔ The ID is used for styling, scripting, and navigation of a specific element in a document.

➔ IDs are used to create internal links so that users can jump to specific sections within a page.

➔ An element with a unique ID called "myid" can be accessed using the document.getElementById("myid") method.

Syntax
//In HTML
<div id="sample" class="mydiv">
    <h4>The ID is used for styling, scripting, and navigation of a specific element in a document.</h4>
    <button class="mybutton" id="mybutton" type="button" onclick="changeStyle()">Toggle Style</button>
</div>

//In JavaScript
<script>
    let element = document.querySelector("#sample");
    let button = document.getElementById("mybutton");
    button.style.color = "white";
    myElement.style.backgroundColor = "black";
</script>

Applies to

This attribute can be used on the following element.

Attribute Element
id Global Attributes

Example

<!DOCTYPE html>
<html>
<head>
    <title>HTML id attribute example</title>
    <style>
        .mydiv {
            border: 2px solid black;
            padding: 30px;
            background: rgb(100, 100, 100, 0.1);
        }
        .mydivchange {
            border: 2px solid red;
            padding: 30px;
            background: #222222;
            color:#fff;
        }        

        input {
            padding: 3px;
        }

        .mybutton {
            margin: 10px 75px;
            padding: 10px;
            border-radius:5px;
            background:#000;
            color:white;
        }
        .mybuttonchange {
            margin: 10px 75px;
            padding: 10px;
            border-radius:5px;
            background:#eee;
            color:black;
        }
    </style>
</head>
<body>
    <div id="sample" class="mydiv">
        <h3>HTML id attribute example</h3>
        <p>The id attribute is used to specify a unique identifier for a single HTML element within a document.</p>
        <h4>ID must be unique within the same HTML document.</h4>
        <h4>The ID is used for styling, scripting, and navigation of a specific element in a document.</h4>
        <button class="mybutton" type="button" onclick="changeStyle()">Toggle Style</button>
    </div>
</body>
<script>
    function changeStyle(){
    let element = document.querySelector("#sample");
    let button = document.querySelector(".mybutton");
    element.classList.toggle("mydivchange");
    button.classList.toggle("mybuttonchange");
    }
</script>
</html>
Try it Now »

Click on the "Try it Now" button to see how it works.