Entonces, básicamente, lo que estoy tratando de hacer es configurar ActionListener para todo el div que estoy generando después de alguna acción del usuario. Dentro de ese div tengo un marcador h1 y algo de texto. Cuando hago clic en h1, ActionListener no responde. Si hago clic en cualquier otro lugar dentro de div, todo funciona correctamente. Estoy configurando ActionListener para div padre con id "lista".
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]; } });así es como genero el 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);¿Cómo hacer que todo el div sea sensible a ActionListener?
No debe actualizar el html con innerHTML , sino agregar un div a su padre con appendChild .
Así es como se vería:
const myElement = document.createElement("div"); myElement.classList.add("note"); /* Other stuff to create the div... */ document.getElementById("list").appendChild(myElement)El problema con la modificación del HTML interno es que esto sobrescribirá cualquier DOM anterior y todos sus eventListeners se separarán.
cf: addEventListener desapareció después de agregar innerHTML