简体   繁体   中英

How to correctly handle event with dynamically added elements?

I am developing a ToDo app with HTML and JS, while got stuck with removing dynamically added elements. Is there any way to remove the selected element?

I have tried to delete an element via selecting its parent and then reaching to the child and removing it. Could not arrange to remove the selected element though. el.removeChild(el.childNodes[0]) removes the element from the beginning. Is there any way to remove the selected-active element?

document.addEventListener('click',function(e){
  if(e.target && e.target.id== 'rem'){
    let el = document.getElementById('uList');
    el.removeChild(el.childNodes[0]); // How to remove the clicked el?
   }
}); 

I expect the code to remove the clicked element, rather deleting the nodes starting from the 0 element.

Many thanks!

document.addEventListener('click', function(e) {
    if (!e.target || e.target.id !== 'rem') {
        return;
    }
    let parent = e.target.parentElement;
    if (!!parent) {
        parent.removeChild(e.target);
    }
}); 

for the parent of parent:

document.addEventListener('click', function(e) {
    if (!e.target || e.target.id !== 'rem') {
        return;
    }
    const parent = e.target.parentElement;
    if (!parent) {
        return;
    }
    const parentOfParent = parent.parentElement;
    parent.removeChild(e.target);
    if (!!parentOfParent) {
        parentOfParent.removeChild(parent);
    }
});

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