javascriptjquerydatasetcustom-data-attributejquery-data

Assigning individual keys of object stored in jQuery.data()


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"

Solution

  • 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.