Can I add arbitrary properties to DOM objects?

ECMAScript 6 has WeakMap which lets you associate your private data with a DOM element (or any other object) for as long as that object exists.

const wm = new WeakMap();
el = document.getElementById("myelement");
wm.set(el, "my value");
console.log(wm.get(el)); // "my value"

Unlike other answers, this method guarantees there will never be a clash with the name of any property or data.

Leave a Comment