5. ID vs Class: Understanding the Difference
Both IDs and classes identify elements, but they serve different purposes.
| Feature | ID | Class |
|---|---|---|
| Purpose | Identifies a particular element | Groups elements for shared styling or behavior |
| Reuse | Should be unique in the document | Can be reused on many elements |
| CSS selector | #main-title |
.card |
| JavaScript access | getElementById() |
querySelectorAll() or other DOM methods |
| Typical use | Unique page section or form field | Reusable cards, buttons, labels, and states |
Example:
<section id="featured-courses" class="course-section">
<article class="course-card">HTML Course</article>
<article class="course-card">CSS Course</article>
<article class="course-card">JavaScript Course</article>
</section>The section has a unique ID and a reusable class. Each course card shares the same class.
Best practice: Use classes for reusable styling and component behavior. Use IDs when you need a unique identifier, a fragment destination, or a specific relationship between elements.
6. The Data Attributes: data-*
Custom data attributes allow developers to store application-specific data on HTML elements. Their names begin with data-.
Basic Syntax
<element data-custom-name="value">Content</element>Example: Product Information
<article
class="product-card"
data-product-id="101"
data-category="laptop"
data-price="45000"
>
<h2>Developer Laptop</h2>
<p>Price: ₹45,000</p>
</article>The custom attributes store values that scripts can read. They do not automatically create visible text, apply styles, or perform calculations.
Data Attribute Naming Rules
- Custom data attribute names begin with
data-. - Use meaningful names such as
data-product-idordata-status. - In HTML, attribute names are ASCII case-insensitive, so lowercase kebab-case names are a clear convention.
- Data attributes are intended for custom data private to the page or application, not for replacing standard HTML attributes.
- Do not store secrets, passwords, private tokens, or authorization credentials in data attributes. Users can inspect page markup and browser DOM data.
Reading Data Attributes with JavaScript
The dataset property provides access to an element's data attributes.
<button
id="product-button"
data-product-id="101"
data-category="laptop"
>
View Product
</button>
<script>
const button = document.getElementById("product-button");
console.log(button.dataset.productId);
console.log(button.dataset.category);
</script>The output is:
101
laptopThe HTML attribute data-product-id is available in JavaScript as dataset.productId. The hyphenated name is converted to camelCase.