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

674
Visualizações
Trying to put onclick on button which was added to DOM by another button but getting error Uncaught TypeError which is about setting 'onclick'

This is my HTML code, it's simple just one div block with button.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Button Problem</title>
    <style>

    </style>
</head>
<body>

    <div class="users">
        <button value ="0" id="button1">CLICK ME</button>
    </div>

    <script src="./script.js"></script>

</body>
</html>

and here is my JavaScript code:

document.getElementById("button1").onclick = function () {
    let el = document.querySelector(".users");
    el.innerHTML += `<button id="button2">LEGIT BUTTON</button>`;
}

document.getElementById("button2").onclick = function(){
    console.log("button2 is working!!!");
}

so in HTML code as you see I have one button in div block. in JavaScript I put onclick on that button and after you click that button new button is added in DOM. but I am getting Error "Uncaught TypeError: Cannot set properties of null (setting 'onclick') at" I want the second onclick to wait for the first onclick to happen to add new button. what should I do?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

you should call document.getElementById("button2").onclick after you add this new button2 to the DOM

about 4 years ago · Juan Pablo Isaza Relatório

0

Based on that code, you are trying to add an event listener to button2 before it has been added to the dom. Try moving it like this to ensure it exists first:

document.getElementById("button1").onclick = function () {
  let el = document.querySelector(".users");
  el.innerHTML += `<button id="button2">LEGIT BUTTON</button>`;
  // it will now exist and you can add a listener
  document.getElementById("button2").onclick = function(){
     console.log("button2 is working!!!");
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

It would be clearer to actually create the dom element and add the listener to it directly after creating it:

document.getElementById("button1").addEventListener("click", function () {

    let el = document.querySelector(".users");
    
    // Create the element using the API
    let btn = document.createElement("button");

    // Add element details (you don't need the ID anymore
    // because we'll use the javascript DOM element directly)
    btn.setAttribute("id", "button2");
    btn.innerText = "LEGIT BUTTON";

    // Add event listener
    btn.addEventListener("click", function(){
        console.log("button2 is working!!!");
    });

    // Append the new button to the element
    el.appendChild(btn);
});

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