LoginSignup
7
4

More than 3 years have passed since last update.

$.dataと$.attr('data-*')の違い

Last updated at Posted at 2016-08-30

jQueryの$.data$.attr('data-*')で取得できる値が違うのは知っていたけど、実際どこまで違うのかわからなかったので調べました。

やったこと

以下のhtmlの各data属性を$.data$.attrで取ってきてtypeofで調べるだけ。

<section class="step__section" data-step="1" data-title="手順1" data-show="true" data-object="{}" data-func="function(){}"></section>

結果

$.dataで取得したもの
typeof $('.step__section').eq(0).data('step');
// => "number" 0

typeof $('.step__section').eq(0).data('title');
// => "string" '手順1'

typeof $('.step__section').eq(0).data('show');
// => "boolean" true

typeof $('.step__section').eq(0).data('object');
// => "object" {}

typeof $('.step__section').eq(0).data('func');
// => "string" 'function(){}'

$.attr('data-*')で取得したもの
typeof $('.step__section').eq(0).attr('data-step');
// => "string" '0'

typeof $('.step__section').eq(0).attr('data-title');
// => "string" '手順1'

typeof $('.step__section').eq(0).attr('data-show');
// => "string" 'true'

typeof $('.step__section').eq(0).attr('data-object');
// => "string" '{}'

typeof $('.step__section').eq(0).attr('data-func');
// => "string" 'function(){}'

$.dataでは関数以外はよしなに型変換してくれるようです。function(){}だけString型で返しているのはおそらくXSS対策なのでしょう。
それにくらべて$.attrはすべてString型で返しています。

どちらが良いかは人と使用する場合によりますが、全部String型で返ってくる$.attr('data-*')のほうが統一感あっていいです。
現場からは以上です。

7
4
1

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