简体   繁体   中英

How to remove a div present inside a div in Javascript

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); })

Call remove on the child:

let childDiv = document.querySelector('.childContainer');
let charDiv = document.querySelector('.characterCard');

searchBtn.addEventListener('click', ()=> {
  charDiv.remove();
})

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()) })

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