简体   繁体   中英

How to delete the parent div when <i> tag inside button clicked?

I am trying to build my to-do list but I am struggling with the delete button.

this is for the button and the code for the eventLisner

let deleteButton = document.createElement('button');
deleteButton.innerHTML = '<i class="fa-solid fa-trash-can"></i>';
deleteButton.classList.add('deleteTask');
task.appendChild(deleteButton);

and the code for the eventLisner

deleteButton.addEventListener('click', function(e){
    let target = e.target;
    target.parentElement.remove();
    });

I just want to know how when clicking the element it deletes the div as the button, now its deleting the button.

What you can do is use the event's composedPath() which includes all the elements/objects that the event bubbles through. Kind of like all the parent chain of the event target until the window object.

What we do is:

  1. Convert the compsoed path to an array [...e.composedPath()]
    • If we click on <i></i> the composed path would be:

      • i
      • button
      • div.container
      • body
      • htmldocument
      • Window
  2. Use Array.prototype.find() to get the container we're trying to delete.
    • The condition I use is to check for the class container
  3. Remove the container

The advantage of using composedPath() is that the element you're trying to get doesn't have to be the direct parent, or any pre-specified distance from the button.

 const deleteButtons = [...document.querySelectorAll('button')] deleteButtons.forEach(button => button.addEventListener('click', function(e){ let pathArray = [...e.composedPath()]; let task = pathArray.find(el => el.classList.contains('container')) task.remove(); }) )
 <div class="container"> <h1>Task 1</h1> <button><i>Delete</i></button> </div> <div class="container"> <h1>Task 2</h1> <button><i>Delete</i></button> </div> <div class="container"> <h1>Task 3</h1> <button><i>Delete</i></button> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM