1

Having a html like this:

<div id="mydiv" data-hoo-foo="bar"></div>

I'm trying the following:

var $mydiv = $('#mydiv');
$mydiv.data('hoo-foo');      // returns 'bar'
$mydiv.data('hoo-foo', 'asdf');
$mydiv.data('hoo-foo');      // returns 'asdf'
$mydiv.attr('data-hoo-foo'); // returns 'bar'

Why is it so?

kub1x
  • 3,272
  • 37
  • 38

1 Answers1

4

Wheny you store data using jQuery .data() method it stores the data internally and doesn't update the HTML5 data- attribute.

What it does, is that it initializes the value in the internal cache from the data- attribute, when you first call the .data() method.

You might get confused because of how the getter version of the .data() method works. When you call $elem.data('someAttr') it:

  1. Looks up the camel case key (e.g. someAttr) in $.cache. If found, returns the value.
  2. Changes the camel case key into the dash separated version (e.g. some-attr) and tries it again. If found, returns the value. This value might originate from the HTML5 data- attribute, as mentioned.

examples:

var $mydiv = $('#mydiv');
$mydiv.data('hoo-foo');        // 'bar' - initialized from the data attribute
$mydiv.data('hooFoo');         // 'bar' - initialized from the data attribute
$mydiv.attr('data-hoo-foo');   // 'bar' - directly from the data attribute

$mydiv.data('hoo-foo', 'asdf');
$mydiv.data('hooFoo');         // 'asdf' - from the stored data by 'hoo-foo' key
$mydiv.data('hoo-foo');        // 'asdf' - from the stored data by 'hoo-foo' key
$mydiv.attr('data-hoo-foo');   // 'bar' - the data attribute remains unchanged

$mydiv.data('hooFoo', 'blah');
$mydiv.data('hooFoo');         // 'blah' - key 'hooFoo' exists
$mydiv.data('hoo-foo');        // 'asdf' - key 'hoo-foo' exists
$mydiv.attr('data-hoo-foo');   // 'bar' - still unchanged

$mydiv.data('hoo-foo', 'ugh'); // this will override the 'hooFoo' key too
$mydiv.data('hooFoo');         // 'ugh'
$mydiv.data('hoo-foo');        // 'ugh'
$mydiv.attr('data-hoo-foo');   // 'bar' - still unchanged

$mydiv.removeData('hoo-foo');  // removes both 'hooFoo' and 'hoo-foo' keys
$mydiv.data('hooFoo');         // 'bar' - key 'hooFoo' adn 'hoo-foo' undefined
                               // initializing as 'hoo-foo' from data- attribute
$mydiv.data('hoo-foo');        // 'bar' - key 'hoo-foo' exists
$mydiv.attr('data-hoo-foo');   // 'bar' - still unchanged

I had kinda hard time figuring this out and didn't have luck finding the complete answer. That's why I'm posting it here. Please correct me if anything isn't precise. I tried to figure out the exact behavior from the code, but it's a heck lotta code, so tried it rather empirically ;)

For reference some other questions touching this issue:

Community
  • 1
  • 1
kub1x
  • 3,272
  • 37
  • 38
  • 1
    Not sure why this has been downvoted even sounds like a duplicate but still can be useful for some other searching reason why – A. Wolff Dec 26 '14 at 12:57