モロモロ工事中です

HTML5が巨人の川相なら、data-属性はHTML5の川相

HTML5,JavaScript — タグ: , — さくら @ 2011/08/25 15:31

意味不明なタイトルですんません。増田にインスパイアされました。

さて HTML5 界隈が騒がしい今日このごろですが、data- 属性というものを皆さんご存知でしょうか?

Twitter のツイートボタン作成ページで作った HTML に入ってる data-via とかのことです。最近色んなところでよく目にしますが、これを使うと任意の DOM 要素に任意の値をセットできるみたいです。

で、この data- 属性なんですが HTML5 の仕様の一部だったみたいです。恥ずかしながらちゃんとした仕様だということを最近知ったのですが、個人的には canvas とか video とかをブッちぎって一番重要な HTML4 からの変更点じゃないかと思います。

てことで本日は、努力家だけど恥ずかしがり屋さんの data- 属性さん(46歳)が実はいぶし銀のスーパースターだということをプロバガンダをしようと思います。

data- 属性は HTML5 の規格の一部

まず超基本的なことですが、data- 属性は HTML5 の規格の一部です。

W3C の HTML5 draft の 3.2.3.8 Embedding custom non-visible data with the data-* attributes に定義されています。

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
3.2.3.8 Embedding custom non-visible data with the data-* attributes

W3C では data- 属性のことを Custom data attributes と呼んでいるようです。日本語では独自データ属性と表記しているサイトが多いと思います(独自データ属性 – グローバル属性 – HTML5 タグリファレンス – HTML5.JP とか)。

重要なのは↓の部分。(英語の仕様を貼っててもアレなんで HTML5.JP さんから引用)

すべての HTML 要素に対して、独自データ属性をいくつでも、どんな値でも指定することができます。
独自データ属性 – グローバル属性 – HTML5 タグリファレンス – HTML5.JP

どの要素に何個でも付けれるらしいです(´・ω・`)便利だねー

てことで HTML5 の独自データ属性を使うと、meta タグとか(Twitter がやってた)、type=”hidden” の input タグとか(form の下位要素じゃないと HTML 的にまずいような)、display:none にした span とか div とか(なんだかねーって感じ)、id や class 属性とか(属性値に制限あり)に、無理やりセットしてたデータをスマートにコーディングできるようになります。

使い方

まず HTML は以下のように書きます。data- に続けてアルファベットと – で任意のキー名を指定します。

<div id="spaceship" data-ship-id="92432"
    data-weapons="laser 2" data-shields="50%"
    data-x="30" data-y="10" data-z="90">宇宙船ちきう号</div>

DOM を使って JavaScript から値を参照する場合は以下のようにコーディングします。

var spaceship = document.getElementById('spaceship');
if (spaceship.dataset) {
    alert(spaceship.dataset.weapons);
    alert(spaceship.dataset.shipId);
} else {
    alert(spaceship.getAttribute("data-weapons"));
    alert(spaceship.getAttribute("data-ship-id"));
}

上のコードでは dataset プロパティが存在するかチェックして dataset に対応していないブラウザをフォールバックしています。手元の Firefox4 が dataset プロパティに対応していないようでしたので、実際にコーディングする際は getAttribute だけで良いような気もします。

dataset プロパティを使用する場合は、キーに – が含まれている場合は Camel にします。(data-ship-id → dataset.shipId)

値をセットする場合は dataset プロパティに代入するか setAttribute を使います。jQuery を使った方が便利ですのでこの辺の例は省略、ってことで興味ある方はご自分でお調べください。

jQuery の場合

jQuery には $.data().data() という似たような名前の関数がありまして、HTML5 の独自データ属性と対応するのは .data() の方なのでご注意ください。$.data() も .data() もプレースホルダを提供する関数なのですが、$.data() の方は完全に jQuery 独自の実装となっています。

で、.data() の方は大方の読者の予想の通り↓のようにコーディングできます。

alert($('#spaceship').data('weapons'));
alert($('#spaceship').data('ship-id'));

値をセットする場合はこんな感じ。

$('#spaceship').data('weapons', 'Gatling gun');
alert($('#spaceship').data('weapons'));

ちなみに、.data() で値をセットしても data- 属性には書き込まず $.cache に値がセットされます。data- 属性に書き込みたい場合は .attr() を使ってください。なんかややこい挙動ですが、なんか理由があってこーなってる気がします。(jQuery のサイトでなんで HTML5 の data- に書き込まないの?って感じのコメントしてる人がいますが華麗にスルーされてますし。)

また、.data() の引数を省略するとデータをオブジェクトで返します。

alert($('#spaceship').data().weapons);

値にはオブジェクトも指定できます。

$('body').data('bar', { myType: 'test', count: 40 });
alert($('body').data('bar').myType);

ぶっちゃけ大して難しいところは無いと思いますので説明はこの辺で。

ということで、いぶし銀 JavaScripter を目指す皆様におかれましては data- 属性で千本バント練習に打ち込むのがよろしいかと思います。

31件のコメント

  1. Dibuja los pétalos de la flor trazando líneas curvas.

    コメント by dibujos de mariposas y flores para pintar en tela — 2018 年 5 月 28 日 @ 06:51
  2. AMAZING WORK GUYS JUST KEEP IT UP !

    コメント by Roman Forest Psychiatric Helpline — 2022 年 6 月 11 日 @ 07:01
  3. Your new valuable key points imply much a person like
    me and extremely more to my office workers. With thanks;
    from everyone of us.

    コメント by Western Psychiatric Helpline — 2022 年 6 月 14 日 @ 16:24
  4. They have truly been a life-changing experience and I couldn’t have asked for better treatment.
    My experience has changed me for the better and gives you everything you need to make a better life on the outside.
    With the therapist’s help and professional advice you truly are given everything, you need to succeed in your life of sobriety.
    Thanks to you all.

    コメント by Opioid Rehab Fort Collins — 2022 年 10 月 5 日 @ 14:24
  5. FB URL Shortener

    [...]we came across a cool web page that you just may appreciate. Take a look should you want[...]

    トラックバック by FB URL Shortener — 2025 年 2 月 15 日 @ 00:25
  6. esports domain

    [...]always a big fan of linking to bloggers that I like but really don’t get quite a bit of link like from[...]

    トラックバック by esports domain — 2025 年 3 月 25 日 @ 17:44
  7. clima en chimalhuacan

    [...]check beneath, are some completely unrelated internet sites to ours, on the other hand, they’re most trustworthy sources that we use[...]

    トラックバック by clima en chimalhuacan — 2025 年 3 月 27 日 @ 00:56
  8. french bulldog

    [...]that would be the finish of this report. Right here you will locate some web sites that we consider you値l value, just click the hyperlinks over[...]

    トラックバック by french bulldog — 2025 年 3 月 27 日 @ 06:30
  9. dog registry

    [...]Every as soon as inside a while we pick blogs that we study. Listed beneath would be the most recent sites that we pick out [...]

    トラックバック by dog registry — 2025 年 3 月 27 日 @ 10:18
  10. french bulldog puppies near me

    [...]below you値l come across the link to some web sites that we feel you’ll want to visit[...]

    トラックバック by french bulldog puppies near me — 2025 年 3 月 27 日 @ 13:19
  11. game ESP downloads

    [...]we came across a cool internet site which you could possibly delight in. Take a look should you want[...]

    トラックバック by game ESP downloads — 2025 年 3 月 27 日 @ 20:37
  12. aimbot marvel rivals

    [...]below you will find the link to some websites that we assume you must visit[...]

    トラックバック by aimbot marvel rivals — 2025 年 3 月 27 日 @ 21:03
  13. securecheats bfv hacks

    [...]that may be the end of this write-up. Here you値l find some websites that we assume you will enjoy, just click the links over[...]

    トラックバック by securecheats bfv hacks — 2025 年 3 月 27 日 @ 22:21
  14. farlight 84 mod

    [...]that would be the end of this post. Here you will come across some sites that we assume you will appreciate, just click the hyperlinks over[...]

    トラックバック by farlight 84 mod — 2025 年 3 月 28 日 @ 01:19
  15. aimbot eft

    [...]below you will find the link to some web-sites that we believe you should visit[...]

    トラックバック by aimbot eft — 2025 年 3 月 28 日 @ 02:19
  16. securecheats valorant hacks

    [...]the time to read or visit the subject material or websites we have linked to below the[...]

    トラックバック by securecheats valorant hacks — 2025 年 3 月 28 日 @ 03:23
  17. mexican candy store

    [...]Every once in a whilst we pick blogs that we study. Listed below are the most current web-sites that we select [...]

    トラックバック by mexican candy store — 2025 年 3 月 31 日 @ 03:04
  18. condiciones climaticas queretaro

    [...]Wonderful story, reckoned we could combine a couple of unrelated information, nonetheless genuinely really worth taking a look, whoa did one find out about Mid East has got much more problerms as well [...]

    トラックバック by condiciones climaticas queretaro — 2025 年 3 月 31 日 @ 13:48
  19. isla mujeres golf cart rental

    [...]we came across a cool internet site that you just may possibly take pleasure in. Take a look for those who want[...]

    トラックバック by isla mujeres golf cart rental — 2025 年 3 月 31 日 @ 19:10
  20. french bulldog puppies for sale $200

    [...]we prefer to honor quite a few other internet internet sites around the web, even if they aren稚 linked to us, by linking to them. Underneath are some webpages really worth checking out[...]

    トラックバック by french bulldog puppies for sale $200 — 2025 年 4 月 1 日 @ 10:51
  21. in vitro fertilization mexico

    [...]very handful of websites that happen to be detailed below, from our point of view are undoubtedly effectively really worth checking out[...]

    トラックバック by in vitro fertilization mexico — 2025 年 4 月 2 日 @ 00:42
  22. linh hoang

    [...]always a big fan of linking to bloggers that I adore but really don’t get quite a bit of link adore from[...]

    トラックバック by linh hoang — 2025 年 4 月 2 日 @ 06:58
  23. french bulldog puppies for sale houston texas

    [...]Here is a good Weblog You may Find Exciting that we Encourage You[...]

    トラックバック by french bulldog puppies for sale houston texas — 2025 年 4 月 2 日 @ 07:06
  24. alexa collins

    [...]just beneath, are quite a few absolutely not associated web pages to ours, on the other hand, they may be surely really worth going over[...]

    トラックバック by alexa collins — 2025 年 4 月 2 日 @ 09:37
  25. 늑대닷컴

    [...]the time to study or go to the content material or web pages we’ve linked to below the[...]

    トラックバック by 늑대닷컴 — 2025 年 4 月 2 日 @ 18:31
  26. family ho

    [...]one of our visitors recently suggested the following website[...]

    トラックバック by family ho — 2025 年 4 月 2 日 @ 21:11
  27. 늑대닷컴

    [...]one of our guests lately suggested the following website[...]

    トラックバック by 늑대닷컴 — 2025 年 4 月 3 日 @ 03:58
  28. wix seo

    [...]very few web-sites that happen to be comprehensive below, from our point of view are undoubtedly well really worth checking out[...]

    トラックバック by wix seo — 2025 年 4 月 3 日 @ 15:35
  29. dog probiotic on amazon

    [...]the time to read or check out the content material or web-sites we’ve linked to below the[...]

    トラックバック by dog probiotic on amazon — 2025 年 4 月 4 日 @ 01:39
  30. fertility institute of nj

    [...]Here is an excellent Weblog You might Find Exciting that we Encourage You[...]

    トラックバック by fertility institute of nj — 2025 年 4 月 4 日 @ 22:54
  31. dr kim acupuncture

    [...]The data talked about in the report are a number of the top offered [...]

    トラックバック by dr kim acupuncture — 2025 年 4 月 4 日 @ 23:16

この投稿へのコメントの RSS フィード。 TrackBack URI

現在、コメントフォームは閉鎖中です。

Copyright © 2025 さくらたんどっとびーず | powered by WordPress with Barecity