Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jQuery, can I store elements using .data() onto another element for fast retrieval?

Can I use the data() function to store a dom element (or a jQuery element) onto another element? (see code below)

Does it store it by value or by reference? Is it good practice?

I want to be able to quickly and easily find the slave element (see code below) of a master element, like so:

$slave = $('.some .path .to .slave');
$master = $('.some .path .to .master');    
$master.data('slave', $slave);    
$master.click(function (){ $(this).data('slave').toggle() });

(obviously the code is stupid, but I'm actually looping through a lot of master and slave elements.)

like image 461
Weboide Avatar asked Sep 30 '11 01:09

Weboide


People also ask

What is jQuery data ()?

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.

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

You can store whatever you want, whether or not you should.

JS variables are references to objects, no? (That's only partially rhetorical–what else would a DOM query return other than a reference? A deep copy?)

like image 101
Dave Newton Avatar answered Oct 25 '22 00:10

Dave Newton