data-*属性
data-*属性は、要素にカスタム(独自、オリジナル)・データを格納するグローバル属性。
| ブラウザ対応 | ![]() ![]() ![]() ![]() ![]() |
|---|
構文
<element data-*="データ">
- *
- 接頭語「data-」の後に、1文字以上の文字を続けて記し、属性名とする。
- データ
- 任意の文字列を指定できる。
要点
- 要素にカスタム・データを格納する。
- 格納したカスタム・データは、JavaScriptなどで動的に使用できる。
- 全てのHTML要素で使用できるグローバル属性である。
- HTML5にて新たに導入された属性である。
サンプルコード
<span data-type="画像">hoge.png</span> <span data-type="画像">hoge.jpg</span> <span data-type="音">hoge.mp3</span>
サンプル
HTMLソースコード
<script>
function getDataType1( $this ) {
var $output = $this.getAttribute( "data-type" );
if( $this.getAttribute( "data-img-type" ) ) {
$output += " " + $this.getAttribute( "data-img-type" );
}
document.getElementById( "sampleOutput1" ).innerHTML = $output;
}
function getDataType2( $this ) {
var $output = $this.dataset.type;
if( $this.dataset.imgType ) {
$output += " " + $this.dataset.imgType;
}
document.getElementById( "sampleOutput2" ).innerHTML = $output;
}
</script>
<ol>
<li><span data-type="画像" data-img-type="png" onclick="getDataType1(this); getDataType2(this);">hoge.png</span></li>
<li><span data-type="画像" data-img-type="jpg" onclick="getDataType1(this); getDataType2(this);">hoge.jpg</span></li>
<li><span data-type="音" onclick="getDataType1(this); getDataType2(this);">hoge.mp3</span></li>
</ol>
<ul>
<li>getDataType1:<span id="sampleOutput1"></span></li>
<li>getDataType2:<span id="sampleOutput2"></span></li>
</ul>
<style scoped="scoped">
ol > li > span {
cursor: pointer;
}
</style>
実際の表示
- hoge.png
- hoge.jpg
- hoge.mp3
- getDataType1:
- getDataType2:
サンプルの動作について
- 「hoge.png」をクリックすると、「getDataType1:」と「getDataType2:」の右横に「画像 png」と表示する。
- 「hoge.jpg」をクリックすると、「getDataType1:」と「getDataType2:」の右横に「画像 jpg」と表示する。
- 「hoge.mp3」をクリックすると、「getDataType1:」と「getDataType2:」の右横に「音」と表示する。




