It's easy to access DOM elements from JavaScript (document.getElementById()
, Document.createElement()
, ...).
Other than storing a reference string (some ID or index) as data attribute or adding an EventListener function to a DOM Element, are there other ways to reference e.g. a JS class instance from a DOM Element?
let instance = new Class();
let element = document.createElement('...');
// something like this:
element.some_reference = instance;
element.some_reference.some_method()
CodePudding user response:
Yes, since DOM elements are JS objects, you can just add any property you want, as you demonstrated in your snippet. This works, and is used by some libraries that wrap DOM elements or need to store non-string data on the elements (for string data, the dataset
is preferred).
However, the big downside of this is that your property names may collide with other libraries, other instances of your own library (if loaded multiple times), or native properties and methods.
Solutions for this problems are using symbols
instead of names, and using a WeakMap
with the element as the key.
CodePudding user response:
It is possible, you can add any property to a DOM element, they javascript values like any other. But it is not a really good idea.
const objInstance = {prop1:1,prop2:2};
document.getElementById('domElement').randomPropValue = objInstance;
console.log(document.getElementById('domElement').randomPropValue);
objInstance.prop1 = 22;
console.log(document.getElementById('domElement').randomPropValue);
<p id="domElement">Some dom element<p>