Take the 2-minute tour ×

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.


share|improve this question
["test1"]["number"] makes no sense in javascript. I don't even know where you were going with that. –  Kevin B Jul 17 '13 at 21:27
["test1"]["number"] evaluates to undefined because that expression tries to access an index ("number") of a 1-element array (["test1"]). Could you clarify what you're trying to achieve? –  Matt Ball Jul 17 '13 at 21:28
Is this what you were looking for? jsfiddle.net/VM8VW/1 your json was invalid, and I assumed what you meant in my first comment –  Kevin B Jul 17 '13 at 21:29
add comment

1 Answer

up vote 5 down vote accepted

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

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

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.

share|improve this answer
It's not your fault, but neither of these work, because div.data("test1") is a string (because it wasn't properly set in the attribute). If it were valid, this would definitely work :) And I don't see what the problem with the second example is, since it returns a reference –  Ian Jul 17 '13 at 21:30
you don't have to re-save it either since it's an object reference, you can just edit them directly -- assuming you fix the invalid json string. Ah, i see you included that in your answer too. –  Kevin B Jul 17 '13 at 21:31
@Ian oh I didn't check the fiddle; I took the OP for its word when it stipulated the value is an object :) –  Pointy Jul 17 '13 at 21:31
@Pointy Yeah, my comment probably made more sense for the OP, not on your answer :) –  Ian Jul 17 '13 at 21:32
@thomas no, that's not correct. If there's no "key" data element, then the result of that function call is undefined. The .data() function behaves differently depending on how many arguments are passed. When it's just one, it fetches any existing value, or else returns undefined. –  Pointy Jul 17 '13 at 23:34
show 5 more comments

Your Answer


