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

74
Views
Render an element inside literal templates with a EventListener

I'm trying to insert an element with an EventListener at a certain point of an element. I can achieve this via appendChild but I want to insert it at a certain point. Like this:

const divT = () => {
  const div = document.createElement("div");
  const div_inside = document.createElement("div");
  div_inside.addEventListener("click", () => {console.log("div_inside")});
  div_inside.innerHTML = "INSIDE";
  div.innerHTML = ` TEST ${div_inside.outerHTML} TEST `;
  return div;
};
document.body.appendChild(divT());

The main problem is the outerHTML does not contain the information of the listener. There is a method to render the HTML with the listener still active?

Thanks in advance

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Find a workaround using insertAdjacentElement and attaching an empty div:

const divT = () => {
  const div = document.createElement("div");
  const div_inside = document.createElement("div");
  div_inside.innerHTML = "Hello World";
  div_inside.addEventListener("click", () => {console.log("div_inside")});
  div.innerHTML = ` TEST <div id="inside"></div> TEST `;
  const div_s = div.getElementsByTagName('div')
  div_s[0].insertAdjacentElement('beforebegin', div_inside)
  return div;
};

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!