Delete button is deleting everything - html and javascript

when I dynamically create a li and add a delete button to it the delete button deletes all elments in the ul. Also, I am unable to create another element in the ul after the delete button is clicked. I am unsure how to fix this. Any help is appreciated!

<!DOCTYPE html>
    <link rel="stylesheet" href="style.css">
    <title>Todo List</title>
    <div id="form">
        <h1>Todo List</h1>
        <input id="todo-input"><button id="add-itemBtn">Add Task</button>
        <ul id="todoContainer">
    <script src="script.js"></script>
 var todo = document.getElementById('todo-input');

// get todo  from input & display to
function addToDo(){
    //var todo = document.getElementById('todo-input');
    document.getElementById('add-itemBtn').addEventListener('click', function(){
        var tag = document.createElement("li");
        var text = document.createTextNode(todo.value); // store todo
        tag.appendChild(text); // append todo to end
        var element = document.getElementById("todoContainer"); //get container you want to store todo in 
        element.appendChild(tag); // append to element
        //style the todo List

        var button = document.createElement("button");
        button.textContent = 'delete';
        button.className = 'newBtn';
        //var text = document.createTextNode('delete'); // store todo
        //tag.appendChild(text); // append todo to end
        var elementBtn = document.getElementById("todoContainer"); //get container you want to store todo in 
        elementBtn.appendChild(button); // append to element

       // elementBtn.onclick = function() {
        //   this.remove();
        elementBtn.addEventListener('click', deleteToDo(elementBtn));


function deleteToDo(elementBtn) {
    elementBtn.onclick = function() {
    var target =;
    while(target.tagName !== 'UL') {
        if(target.tagName === 'LI') {
            return target.parentNode.removeChild(target);
        target = target.parentNode;

function listStyle(tag){ = 'steelblue';
    // = '20px'; = '10px'; = "large";

function btnStyle(button){ = 'red'; = 'white';
    // = '20px';
    // = 'left';
    // = '10px';
    // = "large"; = 'none';

elementBtn is the todoContainer and this inside the onclick is also the todoContainer so that is what you are removing. You are also attaching two event listeners to it.

Try this instead. Don’t run the deleteToDo and pass in the element, just have it to be called by the event listener.

elementBtn.addEventListener("click", deleteToDo);

Then in the deleteToDo function check the target that was clicked is the button and remove the previousElementSibling (the li) and then the button itself.

function deleteToDo(event) {
  const clickTarget =;
  if (clickTarget.matches(".newBtn")) {
1 Like