DEV Community

Discussion on: How to save data for a HTML element in JavaScript

Collapse
 
michaelcurrin profile image
Michael Currin • Edited

Thanks for sharing. I hadn't heard of WeakMap.
I think your two get and set functions, in both cases, add unnecessary complexity and the built methods can make it clearer.

This below is much easier to follow for me and avoids relying on functions to have side effects on a global object.

let elementDataMap = new WeakMap()

const someEl = document.querySelector('#some-el')

elementDataMap.set(
  someEl, {
    prop1: 'val',
    prop2: someComplexValue
});

const elData = elementDataMap.get(someEl);

I can see how putting use of .$dataKey in a function can help in larger application but in the first case you could just set and get directly without the functions.

Also I think it should be mentioned that you can't use this .get on any element to find its data unless you first make a map and send data on the map.

Collapse
 
sarsamurmu profile image
Sarsa Murmu

That's good too. The main thing is the WeakMap after all, you can use it in any way you like to 😀