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.)
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.
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.
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?)
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