1

I have custom data stored on elements using jQuery.data() method.

<div id="mydiv" data-test='{"1":"apple", "2":"banana"}'>Custom data</div>

I know I can access individual keys of the object stored in data-test using

$('#mydiv').data('test')["1"]

But is it ok to re-assign individual keys like this? It works, but it isn't documented. Secondly, on inspecting the element using browser's developer tools, I still see the old value i.e. "apple" in this case. JSFiddle

$('#mydiv').data('test')["1"] = "pear"
TylerH
  • 20,799
  • 66
  • 75
  • 101
user
  • 17,781
  • 20
  • 98
  • 124

2 Answers2

2

Using .data() to set a value, won't change the values in the element while you inspect it, it would store that data internally. If you want to reflect those changes to the DOM element, then you should use .attr() like this,

  $('#mydiv').data('test')["1"] = "pear"
  $('#mydiv').attr('data-test', JSON.stringify($('#mydiv').data('test')));

DEMO

Inspect that particular element to verify the changes.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • Thank you for the tip. I was just reading a similar discussion in comments [here](http://stackoverflow.com/q/17762906/781695). However, I find updating `.attr()` a tedious step. Is there any downside if I don't update it and simply keep using `.data()['key'] = val` method? – user Jul 19 '14 at 06:45
  • @buffer There's no down side in it, you are doing the things in a right way. I just tried to explain you how to reflect the changes in the DOM elements and it is completely unnecessary. – Rajaprabhu Aravindasamy Jul 19 '14 at 06:48
  • 1
    Specifically, jQuery loads the data keys at page load into an internal data array, which is what is used when calls to `.data()` are made. Provided you continue accessing the `data()` method, and not the attributes directly, you wont encounter issues. – Katstevens Jul 19 '14 at 06:52
0

Try this

$('#mydiv').data('test')["1"] = "pear";
$('#mydiv').attr('data-test',function(_,attr){
   return JSON.stringify(attr);
});
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
Balachandran
  • 9,567
  • 1
  • 16
  • 26