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

98
Visualizações
Java Script Button.onclick doesnt'work if wrapped in div

In my project I need to create button dynamically. I wrap it to div and this div is appended to container called tableDoc. My problem is that in this case onclick function doesn't work.
If my button is appended straight to tableDoc with not being wrapped to div before it works fine.

Could you tell me why onclick function doesn't work if wrapped to div?

Example with button wrapped to div before being added to tableDoc:

 Elements.map(item=>{
           
            const div=document.createElement('div');
            ///////adding button////////////////
            var deleteButton = document.createElement("button");

            deleteButton.setAttribute('type','button');
            deleteButton.setAttribute('class',"btn-close");
            deleteButton.setAttribute('aria-label','Close');
            deleteButton.setAttribute('id',item.pk);
            deleteButton.onclick = function() { 
            alert("blabla");
          };
            //////////////////////////////////////////////////////
            div.innerHTML+=item.fields.car+'  '+item.fields.model
            div.appendChild(deleteButton); 
            tableDoc.appendChild(div);
            div.innerHTML+='<br>'


            })

secondary example with button added straight to tableDoc:

Elements.map(item=>{
           
            const div=document.createElement('div');
            ///////adding button////////////////
            var deleteButton = document.createElement("button");

            deleteButton.setAttribute('type','button');
            deleteButton.setAttribute('class',"btn-close");
            deleteButton.setAttribute('aria-label','Close');
            deleteButton.setAttribute('id',item.pk);
            deleteButton.onclick = function() { 
            alert("blabla");
          };
            //////////////////////////////////////////////////////
            div.innerHTML+=item.fields.car+'  '+item.fields.model
            tableDoc.appendChild(deleteButton);
            tableDoc.appendChild(div);
            div.innerHTML+='<br>'


            })
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You remove the event listener by using div.innerHTML+='<br>'.

In the below example, I am creating 2 buttons and append them to 2 divs. The only difference here is that afterwards, I use innerHTML on one of the divs which causes the button to lose its event listener.

That's because innerHTML is a text based function and doesn't carry event listeners with. It operates only on the string representation of the node.

const fooButton = document.createElement('button')
fooButton.onclick = () => console.log("foo")
fooButton.textContent = "foo"
document.getElementById("foo").append(fooButton)

const barButton = document.createElement('button')
barButton.onclick = () => console.log("bar")
barButton.textContent = "bar"
document.getElementById("bar").append(barButton)
document.getElementById("bar").innerHTML += '<br>'
<div id="foo"></div>
<div id="bar"></div>

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