Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the last 3 div inside a div

Tags:

javascript

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.

like image 309
Rakushoe Avatar asked Dec 29 '25 03:12

Rakushoe


2 Answers

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>
like image 199
trincot Avatar answered Dec 31 '25 19:12

trincot


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>
like image 20
Chris Li Avatar answered Dec 31 '25 18:12

Chris Li