Can I add arbitrary properties to JavaScript DOM objects, such as <INPUT>
or <SELECT>
elements? Or, if I cannot do that, is there a way to associate my own objects with page elements via a reference property?
Can I add arbitrary properties to JavaScript DOM objects, such as <INPUT>
or <SELECT>
elements? Or, if I cannot do that, is there a way to associate my own objects with page elements via a reference property?
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.