0

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?

Kacper
  • 1
  • 1

1 Answers1

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

Herobrine
  • 1,661
  • 14
  • 12
  • Thanks for your answer. I did what you suggested, but the problem is still the same. When I'm clicking on h1 the ActionListener is not activating. – Kacper Dec 09 '21 at 20:52