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

Posted by binaryLV on Stack Overflow See other posts from Stack Overflow or by binaryLV
Published on 2010-05-06T12:33:06Z Indexed on 2010/05/06 12:38 UTC
Read the original article Hit count: 145

Filed under:

Hi!

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!

© Stack Overflow or respective owner

Related posts about jQuery