Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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!

like image 986
binaryLV Avatar asked May 06 '10 12:05

binaryLV


People also ask

How to append dom element in jQuery?

Answer: Use the jQuery append() or prepend() method You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements, whereas the prepend() method insert content to the beginning of matched elements.

How to insert div using jQuery?

There are various method to create HTML element inside an HTML document using JQuery. But the simplest of all is append() and prepend() method. Method 1: Using prepend() Method: The prepend() method is used to insert a specified content at the beginning of the selected element.

How to add child div in jQuery?

append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use . prepend() ). The . append() and .


1 Answers

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"​​​​​​​​​​​​​​
like image 186
Nick Craver Avatar answered Nov 07 '22 03:11

Nick Craver