Attributes & Data: Beyond Text

Attributes & Data: Beyond Text in JavaScript: Attributes are the metadata of HTML. Things like , , , and custom attributes.

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-id to store database IDs or data-status for state. Never use CSS classes for logic storage!
  • Standard Attributes: For IDs and classes, use .id and .classList instead of setAttribute. It's cleaner.
  • Boolean Attributes: For attributes like disabled, set them to true or false directly: btn.disabled = true; instead of using a string.

Practice Exercises

  1. The Image Gallery: Create a list of thumbnails. When one is clicked, use getAttribute("src") to update a large main image.
  2. The Data Reader: Create a list of products with data-price attributes. Write a script that finds the most expensive one.
  3. The Attribute Guard: Create a script that finds all <a> tags on the page and automatically adds target="_blank" and rel="noopener" if they point to an external website.