Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

249
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda