Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda