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

246
Vistas
Proper way to add an event after setting html

Let's say I have an element that I want to write the html of, for example:

const tr = ...;
tr.innerHTML = `<td>...</td>`;

Is there a way to write the html so that I have an event listener already on it, or do I need to use a new selector and add the event listener to it, such as with:

tr.querySelector('td').addEventListeneer('click', myFunction);

Or how is this normally done?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can write a Function that takes a template String as input:

const dom = innerString => {
    const holder = document.createElement("DIV");
    holder.innerHTML = innerString;
    return holder.children;
};

Then call it with

const elements = dom("<tr><td>…</td></tr>");

Now you can attach an event listener to the first element with

elements[0].children[0].addEventListener(…);

Then append the elements array to the document

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do it as you suggest, by inserting the HTML and then adding an event listener.

Alternatively you could use the createElement document method to create the element outside of the DOM, attach your event listener and any other properties and then insert it as a whole.

There are performance and security benefits from doing this the second way, but it largely depends on the use case, so feel free to explore this further if this is of importance to you.

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