HTML Data Attributes Guide
Table of contents
- Introduction
- grammar
- Style using data attributes
- Accessing data properties in JavaScript
Introduction
HTML elements can have attributes that are used for any purpose, from accessibility information to style control.
<div aria-label="Names" role="region"></div>
The unsuggested approach is to create your own properties, or re-use existing properties for unrelated features.
<div highlight="true"></div> <div width="large"></div>
There are many bad reasons for doing this. Your HTML will become invalid, which may not have any actual negative effects, but will lose that warm and fuzzy feeling of effective HTML. The most compelling reason is that HTML is an evolving language, and just because properties and values that don't work today do not mean they will never work in the future.
The good news is: you can create your own properties. You just need to prefix them with data-*
and you can do whatever you want!
grammar
It is very convenient to be able to create your own HTML attributes and put your own information into it. Luckily, you can do it! This is what data attributes are used for. They look like this:
<div data-foo=""></div> <div data-size="large"></div>
Data attributes are often called data-*
attributes because they are always in this format. The word data
, then a dash -
, then other text you can think of.
Can you use the data attribute alone?
<div data=""></div>
This may not cause any harm, but you won't be able to get the JavaScript API we'll cover later in this guide. You are actually creating attributes for yourself, which is discouraged, as I mentioned in the introduction.
What should not be done with data attributes
Store content that should be accessible. If the content should be seen or read on the page, don't just put them in the data properties, and make sure the content is somewhere in the HTML content .
<div data-name="Chris Coyier"></div> <div> Chris Coyier </div>
Here is more information about hidden content.
Style using data attributes
CSS can select HTML elements based on attributes and their values.
/* Select any element with this data attribute and value*/ [data-size="large"] { padding: 2rem; font-size: 125%; } /* You can limit it to an element or class or anything else*/ button[data-type="download"] { } .card[data-pad="extra"] { }
This can be attractive. The main style hooks in HTML/CSS are classes, and while classes are great (they have medium specificity and a nice JavaScript method through classList
), the elements either have it or don't have it (basically on or off ). Using data-*
attribute, you can get this turn-on/off feature, as well as the ability to select based on its value at the same specificity level.
/* If the property exists, select */ [data-size] { } /* Select whether the attribute has a specific value*/ [data-state="open"], [aria-expanded="true"] { } /* "Start with..." selector, which means this will match "3" or any character starting with 3, such as "3.14" */ [data-version^="3"] { } /* "Include" means if the value contains the string anywhere */ [data-company*="google"] { }
Specificity of attribute selector
It's exactly the same as the class. We usually consider specificity as a four-part value:
Inline style, ID, class/properties, tags
Therefore, the individual property selectors are 0, 0, 1, 0 . Selectors like this:
div.card[data-foo="bar"] { }
will be 0, 0, 2, 1 . 2 is because there is a class ( .card
) and a property ( [data-foo="bar"]
), and 1 is because there is a tag ( div
).
The specificity of the attribute selector is lower than the ID, higher than the element/tag, the same as the class.
Case-insensitive property values
If you need to correct for possible case inconsistencies in data properties, the property selector provides a case-insensitive variant for this.
/* Will match<div data-state="open"></div> <div data-state="Open"></div> <div data-state="OPEN"></div> <div data-state="oPeN"></div> */ [data-state="open" i] { }
It is the lowercase letter i
in the square bracket selector.
Visualize usage data properties
CSS allows you to extract data attribute values and display them when needed.
/*<div data-emoji="✅"> */ [data-emoji]::before { content: attr(data-emoji); /* Return '✅' */ margin-right: 5px; }<h4 id="Example-of-style-usage"> Example of style usage</h4> <p> You can use the data attribute to specify the number of columns required for the grid container.</p> <pre class="brush:php;toolbar:false"><div data-columns="2"></div> <div data-columns="3"></div> <div data-columns="4"></div>
Accessing data properties in JavaScript
Like any other attribute, you can access the value using the common method getAttribute
.
let value = el.getAttribute("data-state"); // You can also set the value. // Return data-state="collapsed" el.setAttribute("data-state", "collapsed");
But data attributes also have their own special APIs. Suppose you have an element with multiple data attributes (this is absolutely OK):
If your element has a reference, you can set and get the properties like this:
// Get span.dataset.info; // 123 span.dataset.index; // 2 // Set span.dataset.prefix = "Mr. "; span.dataset.emojiIcon = "?";
Note the camel nomenclature in the last line. It automatically converts the kebab-style attribute in HTML (such as data-this-little-piggy
) to camel nomenclature in JavaScript (such as dataThisLittlePiggy
).
This API is arguably not as good as classList
, classList
has clear methods of adding, deleting, switching and replacing, but it is better than nothing.
You can also access inline datasets:
JSON data in data properties
why not? It's just a string that can be formatted into valid JSON (note the quotes, etc.). You can extract the data and parse it as needed.
const el = document.querySelector("li"); let json = el.dataset.person; let data = JSON.parse(json); console.log(data.name); // Chris Coyier console.log(data.job); // Web Person
JavaScript Use Cases
The concept is that you can use data properties to put information into HTML, which JavaScript may need to access to in order to perform certain operations.
A common example is related to database functionality. Suppose you have a "Like" button:
♡
This button can click handler, which performs Ajax requests to the server when clicked to increment the number of likes in the database. It knows which record to update because it gets it from the data properties.
specification
- Selector Level 4 (Work Draft)
- Selector Level 3 (recommended)
- Selector Level 2, Revision 1 (Initial Definition)
Browser support
This browser supports data from Caniuse, which contains more details. The number indicates that the browser supports this feature in this and later versions.
desktop
Mobile/Tablet PC
The above is the detailed content of HTML Data Attributes Guide. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...
