カスタムデータ属性

HTML要素には “id” や “class” のような属性が設定出来ます。

カスタムデータ属性は任意の属性を指定する事が出来ます。

カスタム属性とは

HTML要素に “data-xxx” の形式で任意の属性を指定する事が出来ます。

<div id="sample" data-flg="on">サンプル</div>

用途

属性にデータを持たせたい場合に使用します。

カスタム属性の値の取得

カスタム属性に設定されている値を取得出来ます。

HTML

<div id="sample" data-flg="on">サンプル</div>

java script

HTML要素を取得し、datasetプロパティを使用します。カスタム属性へのアクセスは “data-” を除いたプロパティ名で取得出来ます。

const sample = document.getElementById('sample');
console.log(sample.dataset.flg); // "on" という文字列が取得出来ます。

カスタム属性の値の設定

カスタム属性へ値を設定出来ます。

HTML

<div id="sample" data-flg="on">サンプル</div>

java script

const sample = document.getElementById('sample');
sample.dataset.flg = "off";
console.log(sample.dataset.flg); // "off" という文字列が取得出来ます。

最後に

特にありません。

© DeNnie.Lab All Rights Reserved.