We're looking for a person or people to help audit MDN to find places we could speed up. Is this you or someone you know? Check out the RFP: https://mzl.la/2IHcMiE

この翻訳は不完全です。英語から この記事を翻訳 してください。

HTML5 は、データの拡張性を念頭において設計されているため、特定のエレメントに関連させるべきデータは、定義済みの意味を持つ必要はありません。 data-* 属性 は標準で、なにもハックをせずに意味のあるHTML要素上への非標準属性と、DOMへの追加のプロパテイまたはNode.setUserData()の追加情報格納を可能にします。

HTML syntax

構文は単純です。 エレメントに何らかの属性があり、 その属性の名前が data- で始めまっているとデータ属性です。 例えば視覚的な表現を持ちたくなく、見出しを持たせ追加の情報を格納したいとします 。その場合 data 属性の使用がぴったりです:


JavaScript access

JavaScript でこれらの属性の値を読み出すことはさらに簡単です。 それらはHTMLの名前を使用しgetAttribute() で読み込むことは可能ですが、 もっと単純な方法が標準で定義されています: DOMStringMap を経由して dataset の値を読み出すことができます。

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

var article = document.getElementById('electriccars');
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.


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. 

The main issues to consider are Internet Explorer support and performance. Internet Explorer 11+ provides support for the standard, but all earlier versions do not support dataset. To support IE 10 and under you need to access data attributes with getAttribute()  instead. Also, the performance of reading data-attributes compared to storing this data in a JS data warehouse is poor.

That said, though, for custom element-associated metadata, they are a great solution.

In Firefox 49.0.2 (and perhaps earlier/later versions), the data attributes that exceed 1022 characters will not be read by Javascript (EcmaScript 4).

See also


 このページの貢献者: amanoese
 最終更新者: amanoese,