0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScript:7.data属性(カスタムデータ属性

Posted at

data-*属性って何?

HTML要素に「開発者が自由につけていいカスタム情報(文字列)」を埋め込める機能!

html
<div class="food" data-category="vegetable">
    <div class="food__name">Broccoli</div>
</div>

このdata-category="vegetable"がdata属性(カスタムデータ属性)

何ができるのか?

ts
element.dataset.category // → "vegetable"

つまり、この要素に「vegetable」というカテゴリがついてることがわかる

data=* 属性のメリット

・HTMLの中に「追加の情報」を持たせられる
  ⇒スコア、カテゴリ、IDなど自由
・JavaSriptで簡単に取得できる
  ⇒element.dataset.○○で読める
・CSSでセレクタにも使える
  ⇒div[data-category="junk"]とかで装飾もできる!

他の使用例

タブの切り替え

html
<div data-tab="1">Tab 1</div>
<div data-tab="2">Tab 2</div>

JSでe.target.dataset.tabを見てどのタブか判断

商品にIDを持たせる

html
<button data-product-id="12345">カートに追加</button>

JSでe.target.dataset.productIdを取得して、どの商品か把握

✅ 補足:どう使うのが正しい?

・属性名は data- から始める(必須)
・名前はハイフン区切り(例:data-category、data-score)
・JavaScriptでは camelCase に変換される
   → data-user-id → element.dataset.userId

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?