Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda