I'm trying to put a delete button on each li using JavaScript and to make an event handler that runs when a button is clicked that removes the li. However when I try to add the handler, I get:
Cannot read property 'addEventListener' of null
I think this is because I am referencing a class that not exist before run the function createbtn. So How can I solve this?
The Code:
I set the variables, put querySelector to buttons because I testing how to do it:
var button = document.getElementById("enter"); var input = document.getElementById("userinput"); var ul = document.querySelector("ul"); var list = document.querySelectorAll ("li"); var buttons = document.querySelector (".btn-danger"); var li = document.createElement("li") How I create the button:
function createbtn() { for (var i = 0; i < list.length; i++) { var btn = document.createElement("button"); btn.appendChild(document.createTextNode("Delete")); btn.classList.add("btn", "btn-danger","btn-sm"); list[i].appendChild(btn); } } The function I try to run:
function liDel(){ li.parentNode.removeChild(li); } buttons.addEventListener("click", liDel); This is my fiddle to see all the code.