HTML - Global id Attribute



HTML id is global attribute used to uniquely identify an element within a document, allowing it to be targeted by CSS or JavaScript for styling or manipulation purposes.

The "id" attribute should be unique within the HTML document to ensure proper functionality and adherence to web standards. The name of the id is referred to by the "#" keyword in CSS and Dom methods such as document.getElementById("id_name") in JavaScript.

Syntax

<element id = "id_name" >

The id_name could be anything, buut do not use the same id on other elements.

Applies On

Id attribute is a global attribute, which means it is supported by almost all HTML tags. However structural tags like <html>, <head> does not support id tag.

Example of HTML id Attribute

Below examples will illustrate the HTML id attribute, where and how we should use this attribute!

Id tag applied to paragraph

In the following example, we are creating an HTML document and using the id attributes to style the content of the elements, as follows −

<!DOCTYPE html>
<html>

<head>
<style>
   #exciting {
      background-color: orange;
      border: 1px solid #696969;
      padding: 10px;
      border-radius: 10px;
      box-shadow: 2px 2px 1px black;
   }

   #exciting:before {
      content: 'ℹ️';
      margin-right: 5px;
   }
</style>
</head>

<body>
   <p>
      This is a Normla Text
   </p>
   <p id="exciting">
      HTML id attribute used on this content
   </p>
</body>

</html>

Select element through id Attribute

Let's look into the following example, where we are going to run the script and change background color of paragraph using the id attribute when a button is clicked

<!DOCTYPE html>
<html>

<body>
   <p>This is a paragraph</p>
   <p id="myPara">
      HTML id is global attribute used to uniquely 
      identify an element within a document, allowing 
      it to be targeted by CSS or JavaScript for styling 
      or manipulation purposes.
   </p>
   <button type="button" 
      onclick="changeBackground()">
         change background
   </button>
   <script>
      function changeBackground() {
         var para = document.getElementById("myPara");
         para.style.backgroundColor = "grey";
      }
   </script>
</body>

</html>

Supported Browsers

Attribute Chrome Edge Firefox Safari Opera
id Yes Yes Yes Yes Yes
html_attributes_reference.htm
Advertisements