Skip to main content

HTML id attribute

The HTML id property is used to provide an HTML element a unique identifier.

In an HTML page, you cannot have more than one element with the same id.

Using The id Attribute

The id property of an HTML element gives a unique id. The id property value must be unique inside the HTML content.

The id property in a style sheet is used to point to a specific style declaration. JavaScript also uses it to access and alter the element with the specified id.

Write a hash character (#) followed by an id name in the syntax for id. The CSS properties are then defined within curly braces.

In the following example, we have a <h1> element with the id "myHeader." This <h1> element will be styled in the head section according to the #myHeader style definition:

example
<!DOCTYPE html>
<html>
<head>
<style>
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}
</style>
</head>
<body>
<h1 id="myHeader">My Header</h1>
</body>
</html>
Loading...
note

The id name is case sensitive!

note

The id name must contain at least one character, cannot start with a number, and must not contain whitespaces (spaces, tabs, etc.).

Difference Between Class and ID

A class name can be used by numerous HTML elements on the same page, however an id name can only be used by one HTML element on the same page:

example
<style>
/* Style the element with the id "myHeader" */
#myHeader {
background-color: lightblue;
color: black;
padding: 40px;
text-align: center;
}

/* Style all elements with the class name "city" */
.city {
background-color: tomato;
color: white;
padding: 10px;
}
</style>

<!-- An element with a unique id -->
<h1 id="myHeader">My Cities</h1>

<!-- Multiple elements with same class -->
<h2 class="city">New Delhi</h2>
<p>New Delhi is the capital of India.</p>

<h2 class="city">Moscow</h2>
<p>Moscow is the capital of Russia.</p>

<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
Loading...

Using The id Attribute in JavaScript

JavaScript may also utilize the id property to do various operations for that specific element.

The getElementById() function in JavaScript allows you to get an element with a given id:

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