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

108
Views
H1 within DIV not responding to ActionListener which is set for DIV - pure JavaScript

So basicily what I am trying to do is to set ActionListener for whole div that I'm generating after some user action. Inside of that div I have an h1 marker and some text. When I click on the h1 the ActionListener is not responding. If I click anywhere else inside of div everything is working properly. I am setting ActionListener for parent div with id "list".

  document.getElementById("list").addEventListener("click", function(event) {
        if ( event.target.className === 'note') {
            var id = event.target.id.slice(-1);
            document.getElementById("title").value = titles[id];
            document.getElementById("typedtext").value = notes[id];
        }
   });

this is how I generate the DIV:

    const divNote = document.createElement("div");

    const h1 = document.createElement("H1");
    h1.setAttribute("id", "h" + number_of_notes);
    const titleNode = document.createTextNode(title);
    h1.appendChild(titleNode);

    const textNode = document.createTextNode(text);
    divNote.classList.add("note");
    divNote.setAttribute("id", "n" + number_of_notes);
    divNote.appendChild(h1);
    divNote.appendChild(textNode);
    document.getElementById("list").appendChild(divNote);

How to make the whole div to be sensitive to ActionListener?

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

0

You shouldn't update the html with innerHTML, but rather append a div to your parent with appendChild.

Here's what it would look like:

const myElement = document.createElement("div");
myElement.classList.add("note");
/* Other stuff to create the div... */
document.getElementById("list").appendChild(myElement)

The problem with modifying the innerHTML is that this will overwrite any previous DOM and all of your eventListeners will be detached.

cf: addEventListener gone after appending innerHTML

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!