Table of Contents
Table of contents
Introduction
grammar
Can you use the data attribute alone?
What should not be done with data attributes
Style using data attributes
Specificity of attribute selector
Case-insensitive property values
Visualize usage data properties
Example of style usage
Accessing data properties in JavaScript
JSON data in data properties
JavaScript Use Cases
specification
Browser support
desktop
Mobile/Tablet PC
Home Web Front-end CSS Tutorial HTML Data Attributes Guide

HTML Data Attributes Guide

Apr 11, 2025 am 11:50 AM

HTML Data Attributes Guide

Table of contents

  1. Introduction
  2. grammar
  3. Style using data attributes
  4. 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>
Copy after login

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>
Copy after login

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>
Copy after login
  • 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>
    Copy after login

    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>
    Copy after login

    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"] { }
    Copy after login

    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"] { }
    Copy after login

    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"] { }
    Copy after login

    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] { }
    Copy after login

    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>
    Copy after login

    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");
    Copy after login

    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 = "?";
    Copy after login

    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

    Copy after login

    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
    Copy after login

    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!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

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

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

    It&#039;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.

    Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

    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

    Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

    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&#039;s like this.

    Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

    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.

    A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

    I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

    Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

    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

    Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

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

    Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

    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...

    See all articles