Search code examples
javascriptjqueryjquery-data

how to set property within property in jQuery data()


If I know that a certain data property exists on an element and it is an object, how can I store something as a new property of that data object?

For example, I have this div:

<div id="theDiv" data-test1="{string: 'test 1 data'}"></div>

And I'm trying to set data on it like this:

div.data(["test1"]["number"], 1);

But that is getting me nowhere. And div.data(["test1"]["number"]) = 1; gets me a left-hand side in assignment error.

http://jsfiddle.net/VM8VW/


Solution

  • You have to fetch the value and then re-save it:

    div.data('test1', function(prev) {
      prev.number = 1;
      return prev;
    }(div.data('test1')));
    

    It's probably safe to just do this:

    div.data('test1').number = 1;
    

    but that sort of thing gives me the willies.

    edit — if you want jQuery to understand your JSON as such, it has to be valid:

    <div id="theDiv" data-test1='{"string": "test 1 data"}'></div>
    

    Double quotes only, and property names must also be quoted.