Phase 10 — DOM (Very Important)
Module 33 — Working with Attributes
HTML elements contain attributes that provide additional information about an element. JavaScript allows you to read, modify, add, and remove these attributes dynamically.
Attribute manipulation is commonly used in:
- Forms
- Navigation Menus
- Image Galleries
- Authentication Systems
- Theme Switchers
- Modals
- Accordions
- E-commerce Websites
Overview
| Method | Purpose |
|---|---|
getAttribute() | Get an attribute value |
setAttribute() | Add or update an attribute |
removeAttribute() | Remove an attribute |
toggleAttribute() | Toggle an attribute on or off |
hasAttribute() | Check whether an attribute exists |
dataset | Access custom data-* attributes |
getAttribute()
Returns the value of an attribute.
HTML
1<a id="link" href="https://example.com"> 2 Visit Website 3</a>
JavaScript
1const link = document.getElementById("link"); 2 3console.log(link.getAttribute("href"));
Output
1https://example.com
setAttribute()
Creates a new attribute or updates an existing one.
1const image = document.querySelector("img"); 2 3image.setAttribute("src", "nature.jpg"); 4 5image.setAttribute("alt", "Beautiful Nature");
Output
1<img src="nature.jpg" alt="Beautiful Nature">
removeAttribute()
Removes an attribute from an element.
HTML
1<input type="text" disabled>
JavaScript
1const input = document.querySelector("input"); 2 3input.removeAttribute("disabled");
The input field becomes editable.
toggleAttribute()
Adds the attribute if it doesn't exist, or removes it if it does.
1const button = document.querySelector("button"); 2 3button.toggleAttribute("disabled");
Clicking the button again:
1button.toggleAttribute("disabled");
This makes it useful for enabling and disabling controls.
hasAttribute()
Checks whether an attribute exists.
1const image = document.querySelector("img"); 2 3console.log( 4 5image.hasAttribute("alt") 6 7);
Output
1true
dataset
The dataset property provides access to custom HTML attributes beginning with data-.
HTML
1<button 2 3data-id="101" 4 5data-name="Laptop" 6 7data-price="75000"> 8 9Buy Now 10 11</button>
JavaScript
1const button = document.querySelector("button"); 2 3console.log(button.dataset.id); 4 5console.log(button.dataset.name); 6 7console.log(button.dataset.price);
Output
1101 2Laptop 375000
Updating dataset
1button.dataset.price = "80000";
HTML becomes
1<button 2 3data-price="80000"> 4 5Buy Now 6 7</button>
Practical Example
HTML
1<img 2 3id="photo" 4 5src="cat.jpg" 6 7alt="Cat">
JavaScript
1const photo = document.getElementById("photo"); 2 3console.log( 4 5photo.getAttribute("src") 6 7); 8 9photo.setAttribute( 10 11"src", 12 13"dog.jpg" 14 15); 16 17photo.setAttribute( 18 19"alt", 20 21"Dog" 22 23);
Real-World Example — Product Card
HTML
1<button 2 3class="product" 4 5data-id="5001" 6 7data-category="Electronics"> 8 9View Product 10 11</button>
JavaScript
1const product = document.querySelector(".product"); 2 3console.log(product.dataset.id); 4 5console.log(product.dataset.category);
This approach is widely used in:
- Shopping carts
- Product listings
- Dashboards
- Data tables
Mini Project — Dark Mode Toggle
HTML
1<button id="theme"> 2 3Toggle Theme 4 5</button>
JavaScript
1const button = document.getElementById("theme"); 2 3button.addEventListener("click", () => { 4 5 document.body.toggleAttribute("data-dark"); 6 7});
You can then style the page using CSS:
1body[data-dark]{ 2 background:#222; 3 color:white; 4}
Common Mistakes
Using Properties Instead of Attributes
❌ Wrong
1element.href
Sometimes you need the original HTML attribute.
✅ Correct
1element.getAttribute("href");
Forgetting data-
❌ Wrong
1<button id="10"></button>
For custom values, use:
1<button data-id="10"></button>
Accessing dataset Incorrectly
❌ Wrong
1button.dataset["data-id"];
✅ Correct
1button.dataset.id;
Best Practices
- Use
getAttribute()andsetAttribute()for dynamic attribute manipulation. - Use
datasetto store custom information instead of creating non-standard attributes. - Check for an attribute with
hasAttribute()before using it when appropriate. - Use
toggleAttribute()for boolean attributes such asdisabled,hidden, or custom state attributes. - Prefer semantic HTML attributes (
alt,aria-*,title) to improve accessibility.
Interview Questions
Q1. What is the difference between getAttribute() and accessing an element property?
getAttribute() returns the value defined in the HTML attribute, while a property reflects the current DOM state, which may change after the page loads.
Q2. What is the purpose of dataset?
The dataset property provides an easy way to read and modify custom data-* attributes on HTML elements.
Q3. What does toggleAttribute() do?
It adds the specified attribute if it is missing, or removes it if it already exists.
Q4. When should you use data-* attributes?
Use them to associate custom, non-visible data with HTML elements, such as IDs, categories, product information, or configuration values used by JavaScript.
Summary
In this module, you learned how to work with HTML attributes using JavaScript. You explored methods such as getAttribute(), setAttribute(), removeAttribute(), toggleAttribute(), and hasAttribute(), along with the dataset API for handling custom data-* attributes. These techniques are essential for building dynamic, interactive, and data-driven web applications.
Next Module: Module 34 — DOM Content & Styling, where you'll learn
textContent,innerText,innerHTML,classList,style, CSS variables, and dynamic styling techniques used in professional frontend development.