Home > other >  How to remove an element if it contains a link using querySelectorAll?
How to remove an element if it contains a link using querySelectorAll?

Time:03-16

I tring to remove all list items that contain a link But I only remove the child element and don't know how to remove the parent.

document.querySelectorAll('li a[href^="/chennal/robin"').forEach(e => e.remove());

I tried to do it with loops, but it seems I'm just complicating the code for no reason, especially since it doesn't work.

CodePudding user response:

So you need to walk up the DOM tree back up to the li and remove that.

You either need to use parentNode or parentElement if it is one element up. Or closest('li') if it is more than one element up.

e.parentNode.remove();
e.parentElement.remove()
e.closest('li').remove();
  • Related