Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

254
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda