国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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

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

    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

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    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.

    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)

    What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

    CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

    External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

    ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

    Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

    No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

    CSS Case Sensitivity: Understanding What Matters CSS Case Sensitivity: Understanding What Matters Jun 20, 2025 am 12:09 AM

    CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

    What is Autoprefixer and how does it work? What is Autoprefixer and how does it work? Jul 02, 2025 am 01:15 AM

    Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

    What are CSS counters? What are CSS counters? Jun 19, 2025 am 12:34 AM

    CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

    CSS: When Does Case Matter (and When Doesn't)? CSS: When Does Case Matter (and When Doesn't)? Jun 19, 2025 am 12:27 AM

    In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

    What is the conic-gradient() function? What is the conic-gradient() function? Jul 01, 2025 am 01:16 AM

    Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin

    See all articles