Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to associate javascript objects with DOM nodes?

Tags:

javascript

dom

Can I, and if so, how can I associate javascript objects with DOM nodes? My requirements:

  • real objects, not just JSON-stringified-attributes or so
  • shouldn't leak memory
  • should also work in non-standard browsers like IE8 or so

I was thinking about doing it with a global array that holds the data and putting the indexes in attributes of the nodes, but that would leak memory because there's still a reference from the array to the data when the nodes aren't in th DOM anymore. It's for a web application, so that could be an issue.

like image 839
thejh Avatar asked Jun 17 '26 16:06

thejh


2 Answers

Well, jQuery has the data system, which you could give a try. They say it's free from memory leaks.

like image 54
Spiny Norman Avatar answered Jun 19 '26 06:06

Spiny Norman


Perfect use case for the WeakMap, assuming your targeting newer browsers (chrome 36, edge 12, IE 11, firefox 36, safari 7.1):

let map = new WeakMap();
let node = document.getElementById("unicorn");
let data = {};

window.map.set(node, data);

this wont leak since the keys of the WeakMap are weakly referenced.

like image 35
skav Avatar answered Jun 19 '26 07:06

skav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!