skip to Main Content

Shoppinglist

Hey you,

I’m currently working on a fairly simple shopping list to familiarize myself with javascript.

As you can see in the picture, I want to delete the element next to it when I click on the trashcan.
But this doesn’t quite work as one would imagine and only deletes the top item from my list no matter which trashcan i click on.

My function to create the elements

function addFun(){
    // * List 
    const li = document.createElement('li');
    li.setAttribute('class', 'list_element');
    li.textContent = input.value;
    liste.appendChild(li);
    if(input.value !== ''){
        // * Checkbox
        const checkbox = document.createElement('input');
        checkbox.setAttribute('type', 'checkbox');
        li.insertBefore(checkbox, li.childNodes[0]);
        input.value = '';
        // * trashcan
        const trash = document.createElement('img');
        trash.setAttribute('src', 'https://cdn-icons-png.flaticon.com/512/3209/3209887.png');
        trash.setAttribute('class', 'image');
        li.appendChild(trash);
    }
}

My Eventlistener to remove the elements

document.addEventListener('click', function(e){
    if(e.target.classList.contains('image')){
        deleteIt();
    }
});

function deleteIt(){
    const li = document.querySelector('.list_element');
    li.remove();
}

It took me a long time to get the event handler working as I had never heard of event bubbling before.
I tried a bit with "this" to find a solution, but I wasn’t quite sure what it meant in the context

I would be very happy if someone could look over it and maybe give me a solution or a tip

2

Answers


  1. You can determine the button that was clicked by e.target. From the button you can locate the LI to delete using closest

    document.addEventListener('click', function(e){
        if(e.target.classList.contains('image')){
            deleteIt(e.target);
        }
    });
    
    function deleteIt(whichButton){
        const li = whichButton.closest("li");
        li.remove();
    }
    
    Login or Signup to reply.
  2. Your deleteIt() function is not getting the li that should be deleted.

    You should pass the target button that is clicked to the deleteIt().

    In this way;

        document.addEventListener('click', function(e){
        if(e.target.classList.contains('image')){
            deleteIt(e.target);
        }
    });
    
    function deleteIt(target){
        const li = target.closest("li");
        li.remove();
    }
    

    This way the deleteIt() know which element to delete pricesely.

    I am also new to programming. Sorry if it doesn’t help.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search