Lesson 16 of 21 – HTML ID Attribute
76%

HTML ID Attribute

The HTML id attribute is used to specify a unique identifier for an HTML element. Only one element can use a specific id value within a webpage.

Important: IDs must be unique throughout the HTML document.
Using the ID Attribute

The id attribute identifies a specific HTML element and can be used by CSS and JavaScript.

<h1 id="myHeader">
    Soopro Pathshala
</h1>
CSS Example
<style>

#myHeader{
    background-color:skyblue;
    color:black;
    padding:40px;
    text-align:center;
}

</style>

<h1 id="myHeader">
    Soopro Pathshala
</h1>

The # symbol is used to select an element by id in CSS.

JavaScript Example
document.getElementById("myHeader");

JavaScript uses getElementById() to access a specific element.

Fragment Links
<a href="#contact">
Go to Contact Section
</a>

<h2 id="contact">
Contact Us
</h2>

IDs can be used to jump directly to sections within a webpage.

ID vs Class
ID Class
Must be unique Can be reused
Uses # selector Uses . selector
Higher CSS priority Lower CSS priority

Key Points About HTML ID

  • Unique: Each id must be unique.
  • CSS Styling: Selected using #idname.
  • JavaScript: Accessed using getElementById().
  • Navigation: Useful for internal page links.
  • Higher Priority: Overrides class styles when conflicts occur.
  • Accessibility: Helps connect labels and ARIA attributes.
  • Readable Names: Use meaningful id names.

🧠 Quiz

Which symbol is used before an ID selector in CSS?