1

1) When setting user data (see Live demo) with :

  document.getElementById('myelement1').setAttribute('data-size', 20);

I can see this when analyzing the element with the browser's inspector :

<div id="myelement1" data-size="20">Blah</div>

2) When setting user data with jQuery :

$('#myelement2').data('size', 20);

I can see this when analyzing the element with the browser's inspector :

<div id="myelement2">Blah</div>

Why is the element present in the DOM in 1) but not in 2) ?

How does jQuery .data('size', 20) store the data, and where if it's not in the DOM ? (I'm not advanced enough in JS to find the exact place in the code that does that)

Basj
  • 41,386
  • 99
  • 383
  • 673

2 Answers2

2

jQuery doesn't attach a physical attribute to the element. It keeps an internal object (called cache) where it keeps the data, with a reference to the element that it corresponds to - it isn't stored in the DOM or an attribute.

MrCode
  • 63,975
  • 10
  • 90
  • 112
1

The data for the elements are stored internally, i.e. in a collection local to the jQuery code.

From the documentation of the data method:

"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)."

Note that although the data method doesn't change the data attribute, setting a data attribute will put it in the DOM and also make it available using the data method:

$('#myelement2').attr('data-size', 20);

console.log($('#myelement2').data('size')); // shows 20

Demo: http://jsfiddle.net/kq93n878/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005