Does jQuery.data() store a reference or a deep copy of a jQuery DOM object?
javascript, jquery
Solution
The jQuery object you build with `$('#element_id')` contains
- a reference to the context (the document here)
- the selector
- cached : the length (0 or 1 in your case) and the references of the found dom node
- the pointer to the prototype (so that you can call methods)
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.
Problem
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.