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?

More than 5 years have passed since last update.

HTMLのdata属性について

0
Posted at

カスタムデータ属性とは

  • 要素をスタイリングすることに専念した属性

カスタムデータ属性を使うメリット

  • JavaScriptでアクセスしやすくなる。
  • class属性の冗長化を防げる
  • class属性はスタイル情報の指定要素として割り切った使い方ができるようになる。

JavaScriptでデータ属性にアクセスする

JavaScriptでデータ属性にアクセスする方法は3つある

データセットプロパティを用いる

datasetプロパティを使えば、簡単にデータ属性にアクセスできます。カスタムデータ属性ごとに1つのエントリーを持ったDOMStringMapオブジェクトを返します。

ただし、属性名を配列のキーとして扱うにはチェーンケースからキャメルケースにして使う必要がある。

var owner = restaurant.dataset['ownerName'];
restaurant.dataset['ownerName'] = 'newOwner';

getAtributeとsetAttributeを使う

取り出そうとした属性がない場合getAttributeメソッドはnullあるいは空文字列を返します。このメソッドを使った例は次のようになります。

var restaurant = document.getElementById("restaurantId");
var ratings = restaurant.getAttribute("data-ratings");

既存の属性の値を変更したり、新しい属性を加えるにはsetAttributeメソッドが使えます。

restaurant.setAttribute("data-owner-name", "someName");

jQueryを使った方法

var restaurant = $("#restaurantId");

var owner = restaurant.data("ownerName");
restaurant.data("ownerName", "newName");

参考

いまさら聞けない、HTML5カスタムデータ属性の基本と使いどころ – WPJ

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?