13

I'm trying to build DOM with jQuery and fill it with data that is received with AJAX (data type = json). I'd like to also store this data as an object, attached to a specific DOM element. Does jQuery provide any method for this? The reason I want to do it is because only part of data is initially displayed; other data might be needed later, depending on user actions.

I tried using attr(), but it stores a string "[object Object]" instead of an actual object:

var div = $('<div/>');
div.attr('foo', {bar: 'foobar'});
alert(div.attr('foo')); // gives "[object Object]"
alert(typeof div.attr('foo')); // gives "string"
alert(div.attr('foo').bar); // gives "undefined"

Another way to do this would be by "bypassing" jQuery (div[0].foo = {bar: 'foobar'};), though this seems to be a "dirty workaround", if jQuery happens to already support attaching objects.

Any ideas? Thanks in advance!

2 Answers 2

20

You can use .data() for that purpose, like this:

div.data('foo', { bar: 'foobar' }); //sets it
var obj = div.data('foo'); //gets it

You can see your example code working here just by changing .attr() to .data():

var div = $('<div/>');
div.data('foo', {bar: 'foobar'});
alert(div.data('foo')); // gives "[object Object]"
alert(typeof div.data('foo')); // gives "object"
alert(div.data('foo').bar); // gives "foobar"​​​​​​​​​​​​​​
Sign up to request clarification or add additional context in comments.

Comments

1

I suggest that you use the data method of the jQuery object. This way you can attach custom data (JSON) to the respective DOM element. Here is sample code:

jQuery("div").data("key", /* JSON object */);

later you can get the associated data the following way:

var data = jQuery("div").data("key");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.