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

175
Visualizações
addEventListener no funciona en elementos creados por otra función
let input = document.getElementById("input"); let menu = document.getElementById("menu"); let add = document.getElementById("addtask"); let inner = document.createElement("input"); let task = document.createElement("div"); let deleteBtn = document.createElement("button"); let btnDetails = document.createTextNode("Delete"); let content = document.createElement("p") // HTML structure task.appendChild(content); task.appendChild(deleteBtn); deleteBtn.appendChild(btnDetails) // adding classes & ids task.classList.add("task"); deleteBtn.id ="btn" // events deleteBtn.addEventListener('click', del) // the problem add.onclick = function () { if (input.value !== undefined || input.value.length !== 0) { content.innerText = input.value; let cloned = task.cloneNode(true); if (input.value == ''){ } else { menu.appendChild(cloned) } } else { console.log("empty"); } }; // the problem function del() { console.log("deleted")

Quiero agregar el evento 'clic' en el botón creado por la función (add.onclick) y addEventListener no funciona... aquí está mi bolígrafo: https://codepen.io/mahdtomar/pen/KKvEjO lo tengo , gracias por todo

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

0

Puede hacer uso de la event delegation y usar la closest puede adjuntar un solo oyente en el elemento principal

Note: You shouldn't use id for multiple elements. id should be used to identify only single element in DOM. You are misusing it

 menu.addEventListener("click", e => { if(e.target.closest("button#btn")) { const elem = e.target.closest("div.task"); elem.parentNode.removeChild(elem); } }) 

 let input = document.getElementById("input"); let menu = document.getElementById("menu"); let add = document.getElementById("addtask"); let inner = document.createElement("input"); let task = document.createElement("div"); let deleteBtn = document.createElement("button"); let btnDetails = document.createTextNode("Delete"); let content = document.createElement("p"); // HTML structure task.appendChild(content); task.appendChild(deleteBtn); deleteBtn.appendChild(btnDetails); // adding classes & ids task.classList.add("task"); deleteBtn.id = "btn"; menu.addEventListener("click", e => { if (e.target.closest("button#btn")) { const elem = e.target.closest("div.task"); elem.parentNode.removeChild(elem); } }) add.onclick = function() { if (input.value !== undefined || input.value.length !== 0) { content.innerText = input.value; let cloned = task.cloneNode(true); if (input.value == "") {} else { menu.appendChild(cloned); } } else { console.log("empty"); } };
 .container { max-width: 653px; display: block; margin: 50px auto; } form { background-color: #ddd; width: 100%; padding: 20px; display: flex; justify-content: space-between; align-items: center; } form input { border: none; max-width: 550px; min-width: 300px; width: 500px; height: 50px; padding: 1px 10px; font-size: 20px; border-radius: 20px; } form input::placeholder { padding-left: 10px; } form div { background-color: red; padding: 15px; border: none; border-radius: 10px; color: white; font-weight: bold; margin-left: 20px; cursor: pointer; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .menu { background-color: #ddd; margin-top: 40px; width: 100%; padding: 20px; } .task { display: flex; color: black; justify-content: space-between; margin-bottom: 20px; align-items: center; background-color: white; } .task p { width: 85%; padding: 10px; } .task button { height: 38px; margin-right: 20px; }
 <div class="container"> <form action=""> <input id="input" type="text" name="input" placeholder="Write A Task" /> <div id="addtask">Add Task</div> </form> <div class="menu" id="menu"></div> </div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Su código se ve bien hasta ahora. Dos pequeñas notas:

  1. No use id para los botones de eliminación. porque id es solo para elementos únicos.
  2. deleteBtn.setAttribute("onclick", "del()"); sería trabajo

 let input = document.getElementById("input"); let menu = document.getElementById("menu"); let add = document.getElementById("addtask"); let inner = document.createElement("input"); let task = document.createElement("div"); let deleteBtn = document.createElement("button"); let btnDetails = document.createTextNode("Delete"); let content = document.createElement("p") // HTML structure task.appendChild(content); task.appendChild(deleteBtn); deleteBtn.appendChild(btnDetails) // adding classes & ids task.classList.add("task"); deleteBtn.setAttribute("class", "btn"); // events //deleteBtn.addEventListener('click', del) deleteBtn.setAttribute("onclick", "del(this)"); add.onclick = function () { if (input.value !== undefined || input.value.length !== 0) { content.innerText = input.value; let cloned = task.cloneNode(true); if (input.value == ''){ }else{ menu.appendChild(cloned) } } else { console.log("empty"); } }; function del(e) { e.parentNode.outerHTML = '' console.log("deleted") }
 .container{ max-width: 653px; display: block; margin: 50px auto; } form{ background-color: #ddd; width: 100%; padding: 20px; display: flex; justify-content: space-between; align-items: center; } form input{ border: none; max-width: 550px; min-width: 300px; width: 500px; height: 50px; padding: 1px 10px; font-size: 20px; border-radius: 20px; } form input::placeholder{ padding-left: 10px; } form div{ background-color: red; padding: 15px; border: none; border-radius: 10px; color: white; font-weight: bold; margin-left: 20px; cursor: pointer; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .menu{ background-color: #ddd; margin-top: 40px; width: 100%; padding: 20px; } .task{ display: flex; color:black; justify-content: space-between; margin-bottom: 20px; align-items: center; background-color: white; } .task p{ width: 85%; padding: 10px; } .task button{ height: 38px; margin-right: 20px; }
 <div class="container"> <form action=""> <input id="input" type="text" name="input" placeholder="Write A Task" /> <div id="addtask">Add Task</div> </form> <div class="menu" id="menu"></div> </div>

about 4 years ago · Juan Pablo Isaza Relatório

0

prueba esto:

 document.addEventListener('click', function (e) { if (e.target.id == 'btn') { console.log("deleted") } }, false);
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