Remove all children besides certain 1 or more children in JavaScript

Say I have a ul element with 100 children and I want to remove all children besides 10, 20, 30, 40, 50 (or all besides these with a certain class).

How could I remove all children besides the 5 I mentioned?

This didn’t work:

let rightCol = document.querySelector("#rightCol");
let toSave = rightCol.querySelectorAll('._4-u2._3-96._4-u8');
let toSaveArr = [];

toSave.forEach(()=>{
	toSaveArr.push(toSave);
});

rightCol.innerHTML = '';
rightCol.appendChild(toSaveArr);

Hi @Benos the following might work, but please note I haven’t tested it. Also note how the array ‘toRemove’ is in descending order… this is important because otherwise once you remove an element the indexes will be reset and you will thereafter be removing unexpected items instead:

let myNode = document.querySelector("#rightCol");
var toRemove = [50, 40, 30, 20, 10];
for (var i = 0; i < toRemove.length; i++) {
	var child = myNode.childNodes[toRemove[i] -1];
	child.parentNode.removeChild(child);
}

Hope that helps, if you have any questions please ask.

Hi, thanks Andres. Please review my edited question with my code example.

Hi there Benos,

bearing in mind that javascript is not my forté,
the following example does work. :winky:

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
    background-color: #f0f0f0;
    font: 1em/150% verdana, arial, helvetica, sans-serif;
 }
#list {
    display: inline-block;
    padding: 2em;
    border: 0.06em solid #999;
    background-color: #fff;
 }
</style>

</head>
<body> 

<ul id="list">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
  <li>item 5</li>
  <li>item 6</li>
  <li>item 7</li>
  <li>item 8</li>
  <li>item 9</li>
  <li>item 10</li>
  <li>item 11</li>
  <li>item 12</li>
  <li>item 13</li>
  <li>item 14</li>
  <li>item 15</li>
  <li>item 16</li>
  <li>item 17</li>
  <li>item 18</li>
  <li>item 19</li>
  <li>item 20</li>
  <li>item 21</li>
  <li>item 22</li>
  <li>item 23</li>
  <li>item 24</li>
  <li>item 25</li>
  <li>item 26</li>
  <li>item 27</li>
  <li>item 28</li>
  <li>item 29</li>
  <li>item 30</li>
</ul>

<script>
( function( d ) {
   'use strict';

   var list = d.getElementById( 'list');
   var item = list.getElementsByTagName( 'li' );
   var c;
   var num = [ 4, 9, 14, 19, 24 ];
   var ary = [ ];
   var li;

   for ( c = item.length-1; c >= 0; c -- ){ 
      if ( ( c === num[ 4 ]  ) || ( c === num[ 3 ] ) || ( c === num[ 2 ] ) ||( c === num[ 1 ] ) || ( c === num[ 0 ] ) ) {
            ary.push( item[ c ].textContent );
         }
            list.removeChild( item[ c ] );
      }

   for ( c = ary.length-1; c >= 0; c -- ) {
         li = d.createElement( 'li' );
         li.appendChild( d.createTextNode( ary[ c ] ) );
         list.appendChild( li );
       }

}( document ));
</script>

</body>
</html>

coothead

Another way would be to define the element-indices to keep in an array, and simply not to remove them in the loop… like

const parent = document.querySelector('#rightCol')
const toKeep = [10, 20, 30, 40, 50]

Array.from(parent.children).forEach((item, index) => {
  if (!toKeep.includes(index)) {
  	parent.removeChild(item)
  }
})

Note that by creating an array from the children-node list (which by itself is live), the indices will remain the same even after removing the elements from the DOM – so you don’t need another temporary array to store the elements to keep into and then re-append them.

PS: If you actually just want to keep every 10th item, you might also use a modulo check, like

if (index % 10) {
  parent.removeChild(item)
}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.