HTML – ID

The id attribute is used to specify the unique ID for an element of the HTML document. It allocates the unique identifier which is used by the CSS and the JavaScript for performing certain tasks.

The id name is case sensitive! The id name must contain at least one character, and must not contain whitespaces (spaces, tabs, etc.).

Syntax for Id

The syntax for id is: write a hash character (#), followed by an id name. Then, define the CSS properties within curly braces {}:

<html>
   <head>
      <title>This is document title</title>
   </head>	
      <style>
         #language {
            background-color: #ddd;
            color: white;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <h2 id="language">HTML</h2>
   </body>
</html>

Difference Between Class and Id

A class name can be used by multiple HTML elements, while an id name must only be used by one HTML element within the page:

<html>
   <head>
      <title>This is document title</title>
   </head>	
      <style>
         #language {
            background-color: #ddd;
            color: white;
            padding: 10px;
         }
         .coloredBlock{
            color: #ccc;
         }
      </style>
   </head>
   <body>
      <h2 id="language">HTML</h2>
      <h1 class="coloredBlock">Markup Language</h1>
      <h1 class="coloredBlock">Tags and attributes</h1>
   </body>
</html>

Bookmarks With Id and Links

Bookmarks are used to allow readers to jump to specific parts of a webpage. It can be useful if your page is very long.

To use a bookmark, you must first create it, and then add a link to it.

Then, when the link is clicked, the page will scroll to the location with the bookmark.

<html>
   <head>
      <title>This is document title</title>
   </head>	
      <style>
         #language {
            background-color: #ddd;
            color: white;
            padding: 10px;
         }
      </style>
   </head>
   <body> 
      <a href="#language">Jump to HTML</a>
      <h2 id="language">HTML</h2>
   </body>
</html>
 

Whenever a user clicks on “Jump to HTML”, it will add “#language” to URL and then move the page to HTML section where id=”language” is present.


Id Attribute in Javascript

The id attribute can also be used by JavaScript to perform some tasks for that specific element. JavaScript can access an element with a specific id with the getElementById() method:

<html>
   <head>
      <title>This is document title</title>
      <style>
         #language {
            background-color: #ddd;
            color: white;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <a href="#language">Jump to HTML</a>
      <h2 id="language">HTML</h2>
      <script>    
         var language = document.getElementById("language");   
         language.style.display = "none"; 
      </script>  
   </body>
</html>

Supporting Browsers

ElementChromeIEFirefoxOperaSafari
idYesYesYesYesYes