I'm trying to remove all the divs present with class='characterCard', inside another div with class='childContainer', when a button is pressed.
I've tried .remove() and removeChild() as well, but it doesn't work. Instead when using .removeChild(), I get the following error:
Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
The Character cards are placed inside the childContainers, so the parent element is the childDiv
let childDiv = document.querySelector('.childContainer');
let charDiv = document.querySelector('.characterCard');
searchBtn.addEventListener('click', ()=> {
childDiv.removeChild(charDiv);
})
CodePudding user response:
Call remove on the child:
let childDiv = document.querySelector('.childContainer');
let charDiv = document.querySelector('.characterCard');
searchBtn.addEventListener('click', ()=> {
charDiv.remove();
})
CodePudding user response:
Because there are (likely) more than one .characterCard divs, you need to loop though all matching elements inside of .childDiv and remove one by one.
childDiv.querySelectorAll('.characterCard').forEach(el => el.remove())
let childDiv = document.querySelector('.childContainer');
searchBtn.addEventListener('click', ()=> {
childDiv.querySelectorAll('.characterCard').forEach(el => el.remove())
})
