Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
Reference JS class instance from DOM element

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()
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!