What is data attribute in html

A Complete Guide to Data Attributes

HTML elements can have attributes on them that are used for anything from accessibility information to stylistic control.

What is discouraged is making up your own attributes, or repurposing existing attributes for unrelated functionality.

There are a variety of reasons this is bad. Your HTML becomes invalid, which may not have any actual negative consequences, but robs you of that warm fuzzy valid HTML feeling. The most compelling reason is that HTML is a living language and just because attributes and values that don’t do anything today doesn’t mean they never will.

Good news though: you can make up your own attributes. You just need to prefix them with data-* and then you’re free to do what you please!

It can be awfully handy to be able to make up your own HTML attributes and put your own information inside them. Fortunately, you can! That’s exactly what data attributes are. They are like this:

Data attributes are often referred to as data-* attributes, as they are always formatted like that. The word data , then a dash — , then other text you can make up.

Can you use the data attribute alone?

It’s probably not going to hurt anything, but you won’t get the JavaScript API we’ll cover later in this guide. You’re essentially making up an attribute for yourself, which as I mentioned in the intro, is discouraged.

Читайте также:  Html select получить выбранное значение

What not to do with data attributes

Store content that should be accessible. If the content should be seen or read on a page, don’t only put them in data attributes, but make sure that content is in the HTML content somewhere.

Styling with data attributes

/* Select any element with this data attribute and value */ [data-size="large"] < padding: 2rem; font-size: 125%; >/* You can scope it to an element or class or anything else */ button[data-type="download"] < >.card[data-pad="extra"]

This can be compelling. The predominant styling hooks in HTML/CSS are classes, and while classes are great (they have medium specificity and nice JavaScript methods via classList ) an element either has it or it doesn’t (essentially on or off). With data-* attributes, you get that on/off ability plus the ability to select based on the value it has at the same specificity level.

/* Selects if the attribute is present at all */ [data-size] < >/* Selects if the attribute has a particular value */ [data-state="open"], [aria-expanded="true"] < >/* "Starts with" selector, meaning this would match "3" or anything starting with 3, like "3.14" */ [data-version^="3"] < >/* "Contains" meaning if the value has the string anywhere inside it */ [data-company*="google"]

The specificity of attribute selectors

It’s the exact same as a class. We often think of specificity as a four-part value:

inline style, IDs, classes/attributes, tags

So a single attribute selector alone is 0, 0, 1, 0. A selector like this:

…would be 0, 0, 2, 1. The 2 is because there is one class ( .card ) and one attribute ( [data-foo=»bar»] ), and the 1 is because there is one tag ( div ).

Illustration of a CSS selector including a data attribute.

Attribute selectors have less specificity than an ID, more than an element/tag, and the same as a class.

Case-insensitive attribute values

In case you’re needing to correct for possible capitalization inconsistencies in your data attributes, the attribute selector has a case-insensitive variant for that.

/* Will match */ [data-state="open" i]

It’s the little i within the bracketed selector.

Using data attributes visually

CSS allows you to yank out the data attribute value and display it if you need to.

You could use data attributes to specify how many columns you want a grid container to have.

Accessing data attributes in JavaScript

Like any other attribute, you can access the value with the generic method getAttribute .

let value = el.getAttribute("data-state"); // You can set the value as well. // Returns data-state="collapsed" el.setAttribute("data-state", "collapsed");

But data attributes have their own special API as well. Say you have an element with multiple data attributes (which is totally fine):

If you have a reference to that element, you can set and get the attributes like:

// Get span.dataset.info; // 123 span.dataset.index; // 2 // Set span.dataset.prefix = "Mr. "; span.dataset.emojiIcon = "🎪";

Note the camelCase usage on the last line there. It automatically converts kebab-style attributes in HTML, like data-this-little-piggy , to camelCase style in JavaScript, like dataThisLittlePiggy .

This API is arguably not quite as nice as classList with the clear add , remove , toggle , and replace methods, but it’s better than nothing.

You have access to inline datasets as well:

JSON data inside data attributes

Hey, why not? It’s just a string and it’s possible to format it as valid JSON (mind the quotes and such). You can yank that 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

The concept is that you can use data attributes to put information in HTML that JavaScript may need access to do certain things.

A common one would have to do with database functionality. Say you have a “Like” button:

That button could have a click handler on it which performs an Ajax request to the server to increment the number of likes in a database on click. It knows which record to update because it gets it from the data attribute.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Mobile / Tablet

Источник

Using data attributes

HTML is designed with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.

HTML syntax

The syntax is simple. Any attribute on any element whose attribute name starts with data- is a data attribute. Say you have an article and you want to store some extra information that doesn’t have any visual representation. Just use data attributes for that:

article id="electric-cars" data-columns="3" data-index-number="12314" data-parent="cars">article> 

JavaScript access

Reading the values of these attributes out in JavaScript is also very simple. You could use getAttribute() with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property.

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase).

const article = document.querySelector("#electric-cars"); // The following would also work: // const article = document.getElementById("electric-cars") article.dataset.columns; // "3" article.dataset.indexNumber; // "12314" article.dataset.parent; // "cars" 

Each property is a string and can be read and written. In the above case setting article.dataset.columns = 5 would change that attribute to «5» .

CSS access

Note that, as data attributes are plain HTML attributes, you can even access them from CSS. For example to show the parent data on the article you can use generated content in CSS with the attr() function:

article::before  content: attr(data-parent); > 

You can also use the attribute selectors in CSS to change styles according to the data:

article[data-columns="3"]  width: 400px; > article[data-columns="4"]  width: 600px; > 

You can see all this working together in this JSBin example.

Data attributes can also be stored to contain information that is constantly changing, like scores in a game. Using the CSS selectors and JavaScript access here this allows you to build some nifty effects without having to write your own display routines. See this screencast for an example using generated content and CSS transitions (JSBin example).

Data values are strings. Number values must be quoted in the selector for the styling to take effect.

Issues

Do not store content that should be visible and accessible in data attributes, because assistive technology may not access them. In addition, search crawlers may not index data attributes’ values.

See also

  • This article is adapted from Using data attributes in JavaScript and CSS on hacks.mozilla.org.
  • Custom attributes are also supported in SVG 2; see SVGElement.dataset and data-* for more information.
  • How to use HTML data attributes (Sitepoint)

Found a content problem with this page?

This page was last modified on Jun 30, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

HTML data-* Attribute

The data-* attribute is used to store custom data private to the page or application.

The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.

The stored (custom) data can then be used in the page’s JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).

The data-* attribute consist of two parts:

  1. The attribute name should not contain any uppercase letters, and must be at least one character long after the prefix «data-«
  2. The attribute value can be any string

Note: Custom attributes prefixed with «data-» will be completely ignored by the user agent.

Applies to

The data-* attribute is a Global Attribute, and can be used on any HTML element.

Element Attribute
All HTML elements data-*

Example

Example

Use the data-* attribute to embed custom data:

Browser Support

The numbers in the table specify the first browser version that fully supports the attribute.

Attribute
data-* 4.0 5.5 2.0 3.1 9.6

Источник

Оцените статью