HTML id Attribute

 Night Mode  Light Mode

 

Definition and Usage

The id attribute is a global attribute. It specifies the unique id for an HTML element, which should be unique in the whole document.

Purpose of the id attribute is, to identify an element for changing the behavior by CSS or JavaScript. See the below examples for understanding.

Example :

Changing the background color & width of an element by css using the id attribute.

<p id="myP"> Background color & element width is changed by CSS </p>

<style>
#myP {
background-color: pink;
width: 200px;
}
</style>
Result

Background color and element width is changed by CSS

 
Changing the background color & width of an element by JavaScript using the id attribute.

<p id="firstP"> Background color & element width is changed by JavaScript </p>

<script>
document.getElementById("firstP").style.backgroundColor = "lightgreen";
document.getElementById("firstP").style.width = "200px";
</script>
Result

Background color and element width is changed by JavaScript


 

Note :

Value of the id attribute should not contain on whitespace. Like

<p id="my p"> This is a paragraph </p>

Here are a few tutorials for you to read next:

If you find this tutorial helpful, then please Subscribe to our YouTube Channel for video tutorials, and share this article on social media.

Was this post helpful?

Leave a Comment

Your email address will not be published. Required fields are marked *