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!

In a perfect world, our projects would have unlimited resources and time. Our teams would begin coding with well thought out and highly refined UX designs.

Oh, the Many Ways to Make Triangular Breadcrumb Ribbons

SVG has its own set of elements, attributes and properties to the extent that inline SVG code can get long and complex. By leveraging CSS and some of the forthcoming features of the SVG 2 specification, we can reduce that code for cleaner markup.

You might not know this, but JavaScript has stealthily accumulated quite a number of observers in recent times, and Intersection Observer is a part of that

We may not need to throw out all CSS animations. Remember, it’s prefers-reduced-motion, not prefers-no-motion.

PWA (Progressive Web Apps) have been with us for some time now. Yet, each time I try explaining it to clients, the same question pops up: "Will my users be

It's extremely surprising to me that HTML has never had any way to include other HTML files within it. Nor does there seem to be anything on the horizon that

There are a lot of different ways to use SVG. Depending on which way, the tactic for recoloring that SVG in different states or conditions — :hover,


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment