Jquery, attaching objects (instead of a string attribute) to an element

I am trying to build a DOM with jQuery and populate it with data obtained using AJAX (data type = json). I would also like to save this data as an object attached to a specific DOM element. Does jQuery provide any method for this? The reason I want to do this is because only part of the data is initially displayed; other data may be needed later, depending on the user's actions.

I tried using attr() , but it saves the string “Object Object” instead of the 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 to jQuery's "workaround" ( div[0].foo = {bar: 'foobar'}; ), although this seems like a "dirty workaround" if jQuery already supports object binding.

Any ideas? Thanks in advance!

+6
jquery
source share
2 answers

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

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

You can see that your sample code works here by simply 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"​​​​​​​​​​​​​​ 
+8
source share

I suggest using the data strong> method for a jQuery object. This way you can attach user data (JSON) to the corresponding DOM element. Here is a sample code:

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

later you can get the related data as follows:

 var data = jQuery("div").data("key"); 
+1
source share

All Articles