My span won't delete or not getting targetted

Viewed 44

I don't understand why my span isn't getting deleted when all others is behaving like they supposed. Here's my function.

const item = e.target;

if (item.classList[0] === 'trash-btn') {
    // this works
    const task = item.parentElement.parentElement;
    task.classList.add('vanish');
    task.remove();
}

if (item.classList[0] === 'text-duedate') {
    // this is not working
    item.remove();
}

if (item.classList[0] === 'check-btn') {
    // this works
    const task = item.parentElement.parentElement;
    completed.appendChild(task);
    item.remove();
    completed.addEventListener('click', statusCheck);
}

The div that I am targeting:

<div class="card-date">
    <span class="text-duedate">Due: </span>
    <span class="alert">9/12/22</span>
</div>

Any help is appreciated.

3 Answers

Maybe the text-duedate class is not the first class in the classList, I suggest to use contains

if (item.classList.contains('text-duedate')) {
    // this is not working
    item.remove();
}

NOTE The target element is the element who clicked not who fired the event, so maybe a child element of it, I suggest you use currentTarget.

const item = e.currentTarget;

thank you for the help. This was the only way I could get it to work.

if (item.classList[0] === 'trash-btn') {
    const task = item.parentElement.parentElement;
    task.classList.add('vanish');
    // task.addEventListener('transition-end', function(){
    //     task.remove();
    // });
    task.remove();
}

let elems = document.querySelector('.text-duedate');
elems.remove();


if (item.classList.contains('check-btn')) {
    const task = item.parentElement.parentElement;
    completed.appendChild(task);
    item.remove();
    completed.addEventListener('click', statusCheck);

}

I just ran your code and it seems to work fine

<div class="card-date">
    <span class="text-duedate">Due:</span>
    <span class="alert">9/12/22</span>
</div>

and JS

window.addEventListener('click', (e) => {
    const item = e.target;
    if (item.classList.contains('text-duedate')) {
        item.remove();
    }
})
Related