Loading
The id attribute in HTML is used to uniquely identify a specific element on a web page. It is incredibly useful for
  • Styling specific elements with CSS
  • Accessing elements in JavaScript
  • Creating in-page navigation (anchor links)
Syntax:
<tag id="uniqueId">Content</tag>

Example: apply css with the help of id
<!DOCTYPE html>
<html>
 <head>
  <title>HTML id Example</title>
  <style>
    #main-headiing{
         background-color: beige;
         color: rgb(203, 32, 9);
         padding: 10px;
         text-align: center;
          }
     #paragraph {
          border: 2px solid yellow;
          padding: 8px;
         }
  </style>
 </head>
 <body>
   <h1 id="main-heading">Welcome to Our Website</h1>
   <p id="paragraph">Thank you for visiting</p>
 </body>
</html>

Output:
Uploaded Image

Accessing id in JavaScript
You can easily select and modify elements by their id using JavaScript.

Example:
<!DOCTYPE html>
<html>
 <head>
  <title>Id in JavaScript</title>
  <script>
    function changeText() {
        document.getElementById("main-heading").innerHTML = "Text Changed!";
          }
  </script>
 </head>
 <body>
  <h1 id="main-heading">Original Heading</h1>
  <button onclick="changeText()">Change Text</button>
 </body>
</html>

Output:
Uploaded Image

Text will change by clicking on the button 'Change Text'.

Uploaded Image

Creating Anchor Links with id
You can use id to jump to a specific section of a webpage.

Example:
<!DOCTYPE html>
<html>
 <head>
  <title>Anchor Links with id</title>
 </head>
 <body>
 <a href="#about">Go to About Section</a>

<!-- Some other content -->

  <h2 id="about">About Us</h2>
  <p>This section talks about our company.</p>

 </body>
</html>

Output:
Uploaded Image

By clicking on 'Go to About Section' you will go to section through which this anchor tag is linked with the help of id.

Tips
  • Use id when targeting a single unique element.
  • Avoid reusing the same id in one page.
  • For reusable styles, prefer class over id.
  • When used in CSS or JS, prefix with # (Ex- #main-heading).
Key Point
  • id must be unique within the entire HTML document.
  • It is case-sensitive (#Main is different from #main).
  • An id can be used with CSS, JavaScript, or for page anchors.
  • The id value should not contain spaces.