HTML — Lesson 20
HTML Data Attributes
Storing custom data on elements for JavaScript interaction.
HTML Data Attributes
Data attributes let you store custom information directly on HTML elements. They are accessible through both CSS selectors and JavaScript.
Basic Syntax
<!-- Prefix any attribute name with data- -->
<div
data-user-id="42"
data-product-name="Laptop"
data-in-stock="true"
data-price="999.99"
>Product Card</div>
Accessing via JavaScript
const el = document.querySelector("[data-product-name]");
// Via dataset API (camelCase conversion)
console.log(el.dataset.userId); // "42"
console.log(el.dataset.productName); // "Laptop"
console.log(el.dataset.inStock); // "true" (always a string)
// Set new data attributes
el.dataset.status = "featured";
// Remove a data attribute
delete el.dataset.price;
Using in CSS Selectors
/* Style elements based on data values */
[data-in-stock="true"] {
border: 2px solid green;
}
[data-in-stock="false"] {
opacity: 0.5;
}
/* Attribute substring match */
[data-category^="tech"] {
background: lightblue;
}
Practical Use Cases
<!-- Product cards -->
<div class="product" data-id="7" data-category="electronics">...</div>
<!-- Tab system -->
<button data-tab="profile">Profile</button>
<button data-tab="settings">Settings</button>
<!-- Modal triggers -->
<button data-modal="signup">Sign Up</button>
<button data-modal="login">Log In</button>
JavaScript with Data Attributes
<div id="output"></div>
<button data-action="greet" data-name="World">Say Hello</button>
<button data-action="greet" data-name="HTML">Say Hi</button>
<script>
document.querySelectorAll("[data-action='greet']")
.forEach(btn => {
btn.addEventListener("click", () => {
const name = btn.dataset.name;
document.getElementById("output").innerHTML =
"<p>Hello, " + name + "!</p>";
});
});
</script>
Tip: Use data attributes for data that the JavaScript needs to know about but that is not part of the content. For styling purposes, prefer CSS classes instead.
Practice what you learned in the Deoit Editor — a free, browser-based code editor.
Open Editor →