3

Possible Duplicate:
How does jQuery .data() work?

In jQuery, .data reads the values of HTML5 data-* attributes but when you set/update the values with the data function, it doesn't change the attribute.

​<div id="first" data-foo="attr value" >​​​​​​​​​​​​​​​​​​​​​​​​​​​  </div>

var attr = $('#first').data('foo');
alert(attr); // alerts: attr value

$('#first').data('foo', 'data value');
var data = $('#first').data('foo');
alert(data); //alerts: data value

var attrAgain = $('#first').attr('data-foo');
alert(attrAgain);​ // alerts: attr value

jsFiddle

Where does jQuery store the values? In the docs it is written:

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

But where? I'm trying to understand how expensive using the .data function is.
How can I reach those values without the .data function?

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 1
    That `data` is reading the `data-*` attributes is only an additional feature. It was used to assign arbitrary data to elements long before that. – Felix Kling Mar 04 '12 at 12:27
  • 1
    *"I'm trying to understand how expensive using the .data function is."* Certainly more expensive than getting/setting an attribute. It needs to read the serial number of the element, then look up the data for that serial number stored in `jQuery.cache`. If you need repeated access within the same immediate code, you can speed it up by doing `var d = $(myElem).data()` to reference the associated data directly, then read/write properties on the object like normal. Also, using [`$.data(myElem)`](http://api.jquery.com/jquery.data/) is a little quicker way since it doesn't create a jQuery object. –  Mar 04 '12 at 13:48

1 Answers1

3

jQuery has an internal - to you not immediately accessible - storage space. If you need to update the data-attributes, have a look at Making jQuery.data() selector aware.

jQuery uses that internal storage (nothing but a javascript object, btw.) for two reasons:

  1. to circumvent accessing the DOM for every invocation of .data()
  2. data-attributes may only contain string/int so .data('foo', {bar:"baz"}) wouldn't work as you'd expect

jQuery stores these background information in jQuery.cache according to the data module of jQuery 1.7.1.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
rodneyrehm
  • 13,442
  • 1
  • 40
  • 56