Concept Explanation
Attributes are the metadata of HTML. Things like href, src, value, and custom data- attributes.
Data Attributes (data-*) are the modern standard for storing information directly on an element that isn't visible to the user but is incredibly useful for your code.
Syntax or Core Structure
Managing Attributes
const img = document.querySelector("img");
// Get/Set standard attributes
img.setAttribute("src", "profile.jpg");
console.log(img.getAttribute("alt"));
// The Modern "Data" way
// HTML: <div data-user-id="123" data-role="admin"></div>
const div = document.querySelector("div");
console.log(div.dataset.userId); // "123"
console.log(div.dataset.role); // "admin"
Best Practices
- Use Data Attributes for Logic: Use
data-idto store database IDs ordata-statusfor state. Never use CSS classes for logic storage! - Standard Attributes: For IDs and classes, use
.idand.classListinstead ofsetAttribute. It's cleaner. - Boolean Attributes: For attributes like
disabled, set them totrueorfalsedirectly:btn.disabled = true;instead of using a string.
Practice Exercises
- The Image Gallery: Create a list of thumbnails. When one is clicked, use
getAttribute("src")to update a large main image. - The Data Reader: Create a list of products with
data-priceattributes. Write a script that finds the most expensive one. - The Attribute Guard: Create a script that finds all
<a>tags on the page and automatically addstarget="_blank"andrel="noopener"if they point to an external website.