HTML Attributes – ID & Class

1. What are HTML Attributes?

HTML attributes provide additional information about HTML elements.
They are always written in the opening tag and follow this format:

attribute="value"

Attributes help in:

  • Identifying elements
  • Styling with CSS
  • Accessing elements using JavaScript

2. ID Attribute

2.1 Definition

The id attribute is used to uniquely identify a single HTML element on a webpage.

🔑 Rule:

  • One page → one unique id
  • Two elements cannot have the same id

2.2 Syntax

<tag id="uniqueName">Content</tag>

2.3 Example Code

<h2 id="mainHeading">Welcome Page</h2>
<p>This paragraph belongs to the main section.</p>

Output

2.4 Where id is Used

  • CSS styling
  • JavaScript element access
  • Bookmark links
  • Page sections

2.5 ID in CSS (Preview Example)

<style>
   #mainHeading {
       color: blue;
   }
</style>

2.6 ID for Bookmark Links

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

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

3. Class Attribute

3.1 Definition

The class attribute is used to group multiple elements under a common name.

📌 One class can be used for:

  • Many elements
  • Repeated styling

3.2 Syntax

<tag class="className">Content</tag>

3.3 Example Code

<p class="info">Paragraph one</p>
<p class="info">Paragraph two</p>
<p class="info">Paragraph three</p>

Output

3.4 Class in CSS (Preview Example)

<style>
 .info {
   color: green;
   font-size: 18px;
 }
</style>

4. Multiple Classes on One Element

An element can have more than one class.

<p class="info highlight">Highlighted text</p>

5. Difference Between ID and Class

FeatureIDClass
Uniqueness              Unique                                      Reusable
UsageOne elementMultiple elements                  
CSS Selector#id.class
JS AccessgetElementById()            getElementsByClassName()