0

So im doing Todo App The app works as it should when i want to ADD todos and when i want to DELETE ALL todos it works fine BUT, the problem rises when i want to delete todos individually So when i HARDCODE them into html and press Delete button it works fine but when i add them using an app dynamically it stops working altogether and i cant figure out why...

let addBtn = document.querySelector(".add-item")
let delBtn = document.querySelector(".del-item")
let items = document.querySelector(".items")
let todoItems = document.querySelectorAll(".todo-item")
let delItems = document.querySelectorAll(".delete-todo")

addBtn.addEventListener("click", addTodo)
delBtn.addEventListener("click", clearAllTodos)


delItems.forEach(btn => {
    btn.addEventListener("click", e => {
        targetElem = e.currentTarget
        targetElem = targetElem.parentNode.parentNode.parentNode.parentNode.parentNode
        console.log(targetElem)
        todoItems.forEach(item => {
            if (targetElem === item){
                targetElem.remove()
            }
        })
    })
})

function clearAllTodos() {
    return items.innerHTML = ``
}

function addTodo() {
    let userInput = document.querySelector(".user-input").value

    items.innerHTML += `<li class="todo-item flex items-center justify-between border-b-[1px] border-gray-500 py-4">
    <div class="flex items-center space-x-4 my-2">
        <input type="checkbox" checked="unchecked" class="user-input checkbox" />
        <span class="text-lg">${userInput}</span>
    </div>
    <div>
        <div class="dropdown dropdown-hover">
            <label tabindex="0" class="btn btn-ghost btn-sm m-1">...</label>
            <ul tabindex="0" class="dropdown-content menu p-2 shadow bg-base-100 rounded-box w-52">
                <li><a>Done</a></li>
                <li><a class="delete-todo">Delete</a></li>
            </ul>
        </div>
    </div>
</li>`

}
<!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">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="/dist/output.css">
      <script src="https://cdn.tailwindcss.com"></script>
  
<link href="https://cdn.jsdelivr.net/npm/daisyui@2.38.1/dist/full.css" rel="stylesheet" type="text/css" />
<script src="https://cdn.tailwindcss.com"></script>


    <title>Document</title>
</head>

<body style="font-family: 'Poppins', sans-serif;" class="bg-blue-600 ">
    <div class="flex items-center justify-center mt-40">
        <div style="width: 500px;" class="bg-white rounded-lg text-black">
            <div class=" p-6">
                <div>
                    <input placeholder="Add a new task..." style="border: 1px solid; border-color: rgb(140, 140, 140);"
                        class="user-input outline-none p-3 rounded-md w-full" type="text" name="" id="">
                </div>
            </div>
            <!-- Todo Nav -->
            <div class="pb-6 px-6 border-b-[1px] border-solid border-gray-300  shadow-md">
                <div class="flex justify-between items-center">
                    <ul class="flex text-lg space-x-3">
                        <li class="cursor-pointer transform hover:-translate-y-[2px] duration-150">All</li>
                        <li class="cursor-pointer transform hover:-translate-y-[2px] duration-150">Pending</li>
                        <li class="cursor-pointer transform hover:-translate-y-[2px] duration-150">Completed</li>
                    </ul>
                    <div class="">
                        <button class="btn btn-sm del-item">Clear All</button>
                        <button class="btn btn-sm add-item">Add</button>
                    </div>
                </div>
            </div>
            <!-- todos -->
            <div class="m-6">
                <ul class="items">
                    <li  class="todo-item flex items-center justify-between border-b-[1px] border-gray-500 py-4">
                        <div class="flex items-center space-x-4 my-2">
                            <input type="checkbox" checked="unchecked" class="checkbox" />
                            <span class="text-lg">Stop Procrastinating TODAY</span>
                        </div>
                        <div>
                            <div class="dropdown dropdown-hover">
                                <label tabindex="0" class="btn btn-ghost btn-sm m-1">...</label>
                                <ul tabindex="0" class="dropdown-content menu p-2 shadow bg-base-100 rounded-box w-52">
                                    <li><a>Done</a></li>
                                    <li><a class="delete-todo">Delete</a></li>
                                </ul>
                            </div>
                        </div>
                    </li>
                    
                    <li class="todo-item flex items-center justify-between border-b-[1px] border-gray-500 py-4">
                        <div class="flex items-center space-x-4 my-2">
                            <input type="checkbox" checked="unchecked" class=" checkbox" />
                            <span class="text-lg">Stop Procrastinating TODAY</span>
                        </div>
                        <div>
                            <div class="dropdown dropdown-hover">
                                <label tabindex="0" class="btn btn-ghost btn-sm m-1">...</label>
                                <ul tabindex="0" class="dropdown-content menu p-2 shadow bg-base-100 rounded-box w-52">
                                    <li><a>Done</a></li>
                                    <li><a class="delete-todo">Delete</a></li>
                                </ul>
                            </div>
                        </div>
                    </li>
                    
                    <li class="todo-item flex items-center justify-between border-b-[1px] border-gray-500 py-4">
                        <div class="flex items-center space-x-4 my-2">
                            <input type="checkbox" checked="unchecked" class=" checkbox" />
                            <span class="text-lg">Stop Procrastinating TODAY</span>
                        </div>
                        <div>
                            <div class="dropdown dropdown-hover">
                                <label tabindex="0" class="btn btn-ghost btn-sm m-1">...</label>
                                <ul tabindex="0" class="dropdown-content menu p-2 shadow bg-base-100 rounded-box w-52">
                                    <li><a>Done</a></li>
                                    <li><a class="delete-todo">Delete</a></li>
                                </ul>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</body>
<script src="/dist/app.js"></script>




</html>
  • 1
    Use [event delegation](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of adding several event listeners — it’s more maintainable and applies to dynamically added elements. See [the tag info](/tags/event-delegation/info) and [this Q&A](/q/1687296/4642212). Use the [event argument](//developer.mozilla.org/en/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback): `items.addEventListener("click", ({ target }) => { const btn = target.closest(".delete-todo"); if(btn){`…`} });`. – Sebastian Simon Nov 08 '22 at 21:07
  • 1
    And of course, instead of `targetElem.parentNode.parentNode.parentNode.parentNode.parentNode` etc. just use [`btn.closest(".todo-item").remove();`](//developer.mozilla.org/en/docs/Web/API/Element/closest) or something similar. – Sebastian Simon Nov 08 '22 at 21:10
  • @SebastianSimon ah man this took me all day so easy yet so hard at the same time, took me a while to read that which you wrote lol, i guess thats just learning process, i appreciate the help!! – CrveniFlash Nov 08 '22 at 21:38

0 Answers0