I'm using jQuery.data() to store jQuery DOM object references:
myObj.data('key', $('#element_id'));
I'll be using this a lot (for often the same DOM objects), so I wouldn't like to take up too much memory. Does jQuery store a reference, or does it store a deep copy of the DOM object? In that case I suppose it's better to store the element id instead of the element reference.
The data() is an inbuilt method in jQuery which is used to attach data or get data for the selected elements. Syntax: $(selector). data(para1); Parameter : It accepts an optional parameter “para1” which specifies the name of the data to retrieve for the selected element.
Basically jQuery holds the information you store/retrieve with data(name, value)/data(name) and remove with removeData(name) in an internal javascript object named cache . The rest is just a bit of javascript magic to make it work and keep all the associations right.
A DOM element represents a visual or functional element on the page which was created from the original HTML document. jQuery now is a Javascript library that makes manipulating the DOM easier than with pure Javascript by offering a number of convenience shortcuts.
Basically, . data() is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. . attr() is for setting or checking the DOM element's attribute value and will not touch the jQuery data value.
The jQuery object you build with $('#element_id')
contains
What you store in data (in the node) is the jQuery object. This object doesn't contain any deep copy of the referenced DOM node, so you're not storing a deep copy but just a small object mainly containing a string and a few pointers.
And as the DOM node reference is cached, it's more efficient than just having the id (marginally, as finding a node by id is always fast, but if you had a more complex selector this would make a difference).
So what you do is fine and efficient in my opinion.
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