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

247
Views
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 answers
Answer question

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 Report

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