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

138
Visualizações
Problem with targeting created button with addEventListener

I'm learning vanilla JS and trying to make "To-do list" project. So, idea is simple adding values from form into the list. After that I add edit/remove buttons for every li in list and put the addEventListener to that buttons. For some reason, event listener is targeted on button from form. When I click on button to add new item in list, there is click listener that I want on edit button.

I try different ways to target the right button with parentNodes or childNodes, i find the pretty same code as mine but that don't work for me.

function newItem() {

    let input = document.getElementById("input").value;
    if (input != "") {
        let li = document.createElement("li");
        li.appendChild(document.createTextNode(input));

        let editButton = document.createElement("button");
        editButton.appendChild(document.createTextNode("Edit"));
        li.appendChild(editButton);
        editButton.addEventListener("click", console.log('a'));

        let ul = document.getElementById("list");
        ul.appendChild(li);
        document.getElementById("input").value = "";
    }

    function editItem() {
        alert('e');
    }
}
<!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>To Do!</title>
</head>
<body>
    <h1>To do list</h1>
<div>
    
    <input id = "input" type = "text" placeholder="What do you want to do?" value="">
    <button id = "enter" onclick = "newItem()">Ok</button> 
   
</div>
<p id="proba"></p>
<div>
    <ul id = "list">
      
    </ul>
</div>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>

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

0

You will need to pass a function to your addEventListener method like this: editButton.addEventListener("click", editItem).

Remember that you don't have to add the parameter on the parenthesis of your function.

You can also invoke an anonymous function like this and then add your function to the right block: editButton.addEventListener("click", () => editItem()).

function newItem() {
    
        let input = document.getElementById("input").value;
        if (input != "") {
            let li = document.createElement("li");
            li.appendChild(document.createTextNode(input));
    
            let editButton = document.createElement("button");
            editButton.appendChild(document.createTextNode("Edit"));
            li.appendChild(editButton);
            editButton.addEventListener("click", () => editItem());
    
            let ul = document.getElementById("list");
            ul.appendChild(li);
            document.getElementById("input").value = "";
        }
    
        function editItem() {
            alert('e');
        }
    }
<!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>To Do!</title>
</head>
<body>
    <h1>To do list</h1>
<div>
    
    <input id = "input" type = "text" placeholder="What do you want to do?" value="">
    <button id = "enter" onclick = "newItem()">Ok</button> 
   
</div>
<p id="proba"></p>
<div>
    <ul id = "list">
      
    </ul>
</div>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to pass a function in addEventListener, not just code.

editButton.addEventListener("click", ()=>{console.log('a')});

Or pass it to editItem

editButton.addEventListener("click", editItem);
about 4 years ago · Juan Pablo Isaza Relatório

0

addEventListener takes in a string and a callback function, by passing in console.log('a'), JavaScript is passing in the return value of the console.log, which is undefined. You instead need to wrap it in a function like this: editButton.addEventListener('click', () => { console.log('a'); }).

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