In jQuery can I store elements using .data () on another element for quick retrieval?

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

Does it save it by value or by reference? Is this a good practice?

I want to be able to quickly and easily find the sub element (see code below) of the main element, for example:

$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 sorting through a lot of subordinate and subordinate elements.)

+6
source share
2 answers

You can store whatever you want, regardless of whether you want.

JS variables are object references, no? (This is only partially rhetorical - what else can a DOM request return besides a link? A deep copy?)

+3
source

I know you can do this:

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

Just save the selector in the slave, not the whole object.

0
source

Source: https://habr.com/ru/post/898334/


All Articles