HTML data attributes: storing information for CSS and JavaScript
Attach your own values to elements with data attributes and read them from JavaScript and CSS.
In this lesson you will
- Create data attributes
- Read them with JavaScript dataset
- Style with attribute selectors
- Avoid unsafe uses
About 13 minutes
Giving your HTML a memory
Priya’s menu page lists twenty products. When a customer clicks “Add to basket”, the page needs to know which product, its price and its ID. Where does that information live? You could hide it in a class name, or parse it out of the text, but both are fragile. HTML offers a clean place for it: data attributes.
What a data attribute is
Any attribute whose name begins with data- is yours to invent. Browsers ignore it for display, but JavaScript and CSS can read it. The name after the dash uses lower case letters and hyphens.
<article class="product" data-id="42" data-price="450" data-category="bread">
<h3>Sourdough loaf</h3>
<p>Rs 450</p>
<button type="button">Add to basket</button>
</article>
The information is attached to the element it describes, so there is never any confusion about which price belongs to which product.
Reading data attributes with JavaScript
const product = document.querySelector('.product');
console.log(product.dataset.id); // "42"
console.log(product.dataset.price); // "450"
console.log(product.dataset.category); // "bread"
// change one
product.dataset.price = '480';
Every data-* attribute appears on the element’s dataset object. A name with hyphens, such as data-first-name, becomes camelCase in JavaScript: dataset.firstName. Values are always strings, so convert them with Number() when you need to calculate.
Press Run and click each button. The script reads the data-price from the button that was clicked. Add a third button with data-name=”Scone” and data-price=”150″.
<button data-name="Bread" data-price="450">Bread</button>
<button data-name="Cake" data-price="2400">Cake</button>
<p id="out">Click a button</p>
<script>
document.querySelectorAll('button').forEach(function(b){
b.addEventListener('click', function(){
document.getElementById('out').textContent = b.dataset.name + ' costs Rs ' + b.dataset.price;
});
});
</script>
Copy one of the button lines and change the name and price. The script already handles every button.
<button data-name="Bread" data-price="450">Bread</button>
<button data-name="Cake" data-price="2400">Cake</button>
<button data-name="Scone" data-price="150">Scone</button>
<p id="out">Click a button</p>
<script>
document.querySelectorAll('button').forEach(function(b){
b.addEventListener('click', function(){
document.getElementById('out').textContent = b.dataset.name + ' costs Rs ' + b.dataset.price;
});
});
</script>
Notice that the script did not change when you added a third button. This is the great benefit of data attributes: the page’s data lives in the HTML, and the code stays small and general.
Using data attributes in CSS
CSS can select elements by their data attributes, which lets you style based on state without extra classes.
.product[data-category="bread"] { border-left: 4px solid #C98A3E; }
.product[data-stock="0"] { opacity: .5; }
[data-status="new"]::after { content: " NEW"; color: #5A28C8; font-weight: 700; }
Even better, a data attribute’s value can be shown through the attr() function in generated content, for example a tooltip made with content: attr(data-tip).
Practical uses
- Filters. Mark each item with
data-category, then show or hide by matching it. - Tabs and accordions. A button’s
data-target="panel-2"says which panel it controls. - Analytics and tracking.
data-track="signup-button"marks elements to measure. - Configuration.
data-autoplay="true"passes options to a script without editing the script. - Product and user IDs. The most common use of all.
What not to put there
Data attributes are visible to anyone who views the page source. Never put passwords, private tokens or personal details in them. Also do not hide content that visitors should see, or that search engines should read, inside an attribute. Important text belongs in the page itself.
A good test: if the information is meant for people, put it in the content. If it is meant for your own code, a data attribute is a good home.
Data attributes versus classes and ids
- Use a class to describe how something should look or what group it belongs to.
- Use an id for a one-off target such as an in-page link.
- Use a data attribute to attach a value that code needs to read, such as a price or an identifier.
Write the markup for an event card: an article with data-id=”7″, data-date=”2026-12-05″ and data-seats=”30″, a heading and a button.
<!-- your article here -->
Put all three data attributes inside the opening article tag.
<article data-id="7" data-date="2026-12-05" data-seats="30">
<h3>Cake decorating workshop</h3>
<button type="button">Reserve a seat</button>
</article>
A bigger example: a simple filter
Here is how data attributes make real features short. Imagine the menu page with a row of category buttons. Each product card has a data-category, and each button has a data-filter. One short script shows or hides cards by comparing the two.
<button data-filter="all">All</button>
<button data-filter="bread">Bread</button>
<button data-filter="cake">Cakes</button>
<article class="item" data-category="bread">Sourdough</article>
<article class="item" data-category="cake">Chocolate cake</article>
<article class="item" data-category="bread">Rye loaf</article>
<script>
document.querySelectorAll('[data-filter]').forEach(function (btn) {
btn.addEventListener('click', function () {
var wanted = btn.dataset.filter;
document.querySelectorAll('.item').forEach(function (it) {
it.hidden = wanted !== 'all' && it.dataset.category !== wanted;
});
});
});
</script>
Adding a new category means adding a button and tagging some cards. You never touch the script. That is the sign of a good design: the data lives in the HTML and the behaviour is written once. The same pattern powers tabs, sorting, sliders and countless features you will build in the JavaScript course.
The hidden attribute removes an element from view and from screen readers in one step, and you can switch it with el.hidden = true.
Naming conventions that keep projects tidy
- Use clear, specific names:
data-product-idbeatsdata-x. - Keep the same name for the same idea across the site, so a teammate can guess it.
- Prefer a few well-chosen attributes over dozens of tiny ones on every element.
- For true on or off states, you can use a presence-only attribute such as
data-featuredand test it in JavaScript withel.hasAttribute('data-featured').
Treat the names as a small, quiet contract between your HTML and your code. Write them down once in a comment at the top of your script, and future you will be grateful.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What must a custom data attribute’s name start with?
custom-data-x-js-
Custom attributes should begin with data- to be valid HTML.
How do you read data-first-name in JavaScript?
el.firstNameel.dataset.firstNameel.data-first-nameel.getName()
Hyphenated names become camelCase on the dataset object.
What type are dataset values?
- Numbers
- Strings
- Booleans
- Arrays
All dataset values are strings. Convert them when needed.
Which should never go in a data attribute?
- A product ID
- A password or private token
- A category name
- A date
Anyone can read attributes by viewing the source.
Which selector styles elements with data-stock="0"?
.data-stock[data-stock="0"]#data-stockdata-stock::0
Square brackets select elements by attribute.
Summary
- data-* attributes attach custom values to elements.
- JavaScript reads them through dataset as strings.
- CSS can select and display them.
- Never store secrets there.
Questions
Can I invent any name after data-?
Yes, use lower case letters, numbers and hyphens, for example data-product-id.
Are data attributes bad for SEO?
They are ignored for ranking, so do not place important text in them.
Do they slow the page?
Not noticeably. Thousands of them on a huge page could add weight, but normal use is fine.
