data-*属性値をJavaScriptで取得
data-*属性の値をJavaScriptで取得する方法は、2つある。
element.getAttribute( attributeName )メソッドを使う方法
<span data-img-type="png">hoge.png</span>
上記のような「data-img-type」属性にアクセスするには、下記のJavaScriptコードのように、element.getAttribute( attributeName )メソッドの引数に、属性名「data-img-type」を指定する。
elementReference.getAttribute( "data-img-type" );
datasetプロパティからアクセスする方法
<span data-img-type="png">hoge.png</span>
上記のような「data-img-type」属性にアクセスするには、下記のJavaScriptコードのように、属性名の「data-」より後の部分をキャメルケースにしたものを、datasetプロパティにピリオドで繋げて、アクセスできる。
elementReference.dataset.imgType;
サンプル
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:」の右横に「音」と表示する。