HTML id Attribute

HTML Tutorial

HTML id Attribute

In HTML id Attribute is used to uniquely identify a single element on a page.

It is commonly used for CSS styling, JavaScript access, and page navigation (anchors).


 1. What Is the id Attribute?

  • Assigns a unique name to an HTML element

  • Must be unique (only one element per page)

  • Used with CSS (#) and JavaScript

<h1 id="mainTitle">Welcome</h1>

 2. Basic Example

HTML

CSS

 Only the element with id="intro" gets styled


 3. Using id with <div>

 Very common for page layout


 4. id in JavaScript (Very Common)


 

 Direct access to a single element


 5. id for Page Navigation (Anchor Links)


 

 Clicking the link scrolls to the element with that id


 6. id vs class (Important Difference)

Featureidclass
UniqueYesNo
ReusableNoYes
CSS selector#id.class
JavaScriptgetElementById()getElementsByClassName()
Use caseSingle elementGroup of elements

Rule of thumb

  • Use id for unique elements

  • Use class for repeated styling


 7. Naming Rules & Best Practices

  •  Must be unique
  •  Case-sensitive
  • No spaces (use - or _)
  •  Start with a letter

Good

<div id="main-content"></div>

Bad

<div id="Main Content"></div>
<div id="123box"></div>

 Common Mistakes

  •  Using same id on multiple elements
  •  Confusing id with class 
  •  Forgetting # in CSS
  • Overusing id for styling instead of class

Key Points to Remember

  • id uniquely identifies one element

  • Selected using # in CSS

  • Used heavily in JavaScript

  • Ideal for anchors & unique layout parts

  • Never repeat the same id

You may also like...