Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jQuery.data() store a reference or a deep copy of a jQuery DOM object?

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.

like image 995
Carvellis Avatar asked Dec 08 '12 10:12

Carvellis


People also ask

What is jQuery data function?

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.

How have you stored and referenced data in your jQuery code?

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.

What is the difference between jQuery and DOM?

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.

How add data attribute in jQuery?

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.


1 Answers

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.

like image 145
Denys Séguret Avatar answered Sep 29 '22 22:09

Denys Séguret