When I store an object like {a: 1, b: 2 }
in jQuery's data, does it copy the object or save a reference to it?
I have a huge object and I want different elements to store different references from different points to the same object, and I don't want it to get copied.
Like
var obj = {
a: {
one: 1, two: 2
},
b: {
apple: 'yummy', banana: 'ehh'
}
c: {
d: {
'jQuery': jQuery
}
e: ['You get the point']
}
};
$('div').data('info', obj.b);
$('#JQ').data('jq_reference', obj.c.d.jQuery);
The data() method attaches data to, or gets data from, selected elements. Tip: To remove data, use the removeData() method.
Alternatively, you can also use the jQuery data() method (jQuery version >= 1.4. 3), to get the data-attribute of an element using the syntax like $(element). data(key) . That means in the above example to get the data-id using data() method you can use the statement like $(this).
$('div'). attr('data-info', 1); $('div')[0]. setAttribute('data-info',1); In order to access an element with the attribute set, you can simply select based on that attribute as you note in your post ( $('div[data-info="1"]') ), but when you use .
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
According to my jsfiddle test, it stores a reference.
If I do this:
$('div').data('info', obj.b);
obj.b.apple = 'bleuch';
alert($('div').data('info').apple);
It alerts "bleuch", showing that a reference to the original object is being stored.
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