Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does .data() store the values? [duplicate]

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?

like image 723
gdoron is supporting Monica Avatar asked Aug 08 '26 02:08

gdoron is supporting Monica


1 Answers

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.

like image 161
rodneyrehm Avatar answered Aug 09 '26 15:08

rodneyrehm