We can remove all child nodes from an element with a few node properties.
For instance, if we have the following HTML:
<div>
<p>
foo
</p>
<p>
bar
</p>
<p>
baz
</p>
</div>
Then we can remove all the p
elements by writing:
const node = document.querySelector('div')
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
We get the div with document.querySelector
.
Then we use a while loop to check if there’re any child nodes left with node.hasChildNodes
.
And if there are any left, we call node.removeChild
with node.lastChild
to remove the last child node.