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

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

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

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 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