简体   繁体   中英

Only remove the one child of the element, how to remove child with specific button?

In this, I want to remove the child with specific remove button. but when i run this code, it will remove only one activity that i have inserted in the input.

function addItemTodo(text){
    list = document.getElementById("todo");

    item = document.createElement('li');
    item.innerText = text;

    trash = document.createElement('button');
    trash.classList.add('btn1');
    trash.addEventListener("click", removeActivity);

    icon_trash = document.createElement('i');
    icon_trash.classList.add('fas','fa-trash-alt','fa-2x');

    check = document.createElement('button');
    check.classList.add('btn2');

    icon_check = document.createElement('i');
    icon_check.classList.add('fas','fa-check','fa-2x');

    item.appendChild(trash);
    trash.appendChild(icon_trash);
    item.appendChild(check);
    check.appendChild(icon_check);
    list.appendChild(item);
}

//if user click on the button, remove the activity from the list of Activity

function removeActivity(){
    list.removeChild(item);
    console.log("item removed!");
}

Change function removeActivity() to below code

function removeActivity(){
 var listItems = document.getElementsByTagName("li"); 
  for (var i = 0; i < listItems.length; i++) {
   listItems[i].onclick = function() {
  this.parentNode.removeChild(this);
  }
   }
 }

I have made a working demo on codepen have a look

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