Skip to content

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");

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

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

    function editItem() {
<!DOCTYPE html>
<html lang="en">
    <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>
    <h1>To do list</h1>
    <input id = "input" type = "text" placeholder="What do you want to do?" value="">
    <button id = "enter" onclick = "newItem()">Ok</button> 
<p id="proba"></p>
    <ul id = "list">
<script type="text/javascript" src="todo.js"></script>


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);