LoginSignup
0
1

More than 1 year has passed since last update.

’data-*’表現をよく見るから調べると「データ属性」って言うらしい

Posted at

‘data-*’の正体

HTML要素に追加情報を格納できるHTML属性

使用例

‘data-*’属性がない時

<article id="electric-cars">
    ...
</article>

電気自動車の記事が書かれてるという情報が分かりそうです。

‘data-*’属性がある時

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

‘data-*’属性を加える事で、3つのトピックが用意されているこの記事は12314個目電気自動車以外の車の記事もあるかもしれない
これらの情報が追加で分かりました。

‘data-*’属性を使うと何が嬉しいの?

JavaScriptでおこなうデータ取得がシンプルになります。
実際に下記で確認してみます。

‘data-*’属性がない時

const article = document.getElementById('electric-cars');

article.getAttribute('columns'); // "3"
article.getAttribute('indexNumber'); // "12314"
article.getAttribute('parent'); // "cars"

getAttribute()を何度も呼び出しています。
少しカッコ悪さを感じてしまいますね…。

‘data-*’属性がある時

const article = document.getElementById('electric-cars');

article.dataset.columns // "3"
article.dataset.indexNumber // "12314"
article.dataset.parent // "cars"

可読性が上がった気がします。

参考リンク🙏🏻

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1