removing the last 3 divs inside the div using native javascript
It should first look like this:
<div id="name">
<div>one</div>
<div>two</div>
<div>three</div>
<div>four</div>
<div>five</div>
</div>
After removing it:
<div id="name">
<div>one</div>
<div>two</div>
</div>
I tried removing it by assigning individual id names on them but its impossible to track the changes since its constantly changing and shuffling.
The last three can be identified with .slice(-3) on the node list (when converted to array):
const parent = document.querySelector("#name");
[...parent.children].slice(-3).forEach(parent.removeChild.bind(parent));
<div id="name">
<div>one</div>
<div>two</div>
<div>three</div>
<div>four</div>
<div>five</div>
</div>
You can select the last 3 divs with :nth-last-child(-n+3) and delete them in an iteration
document.querySelectorAll('#name > div:nth-last-child(-n+3)').forEach(n => {
n.parentNode.removeChild(n)
})
<div id="name">
<div>one</div>
<div>two</div>
<div>three</div>
<div>four</div>
<div>five</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With