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!
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.
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.
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 .
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With