Remove all children besides certain 1 or more children in JavaScript

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