How would I go about removing all of the child elements of a DOM node in JavaScript?
Say I have the following (ugly) HTML:
&
myNode.querySelectorAll('*').forEach( n => n.remove() );
This answers the question, and removes “all child nodes”.
If there are text nodes belonging to myNode
they can’t be selected with CSS selectors, in this case we’ve to apply (also):
myNode.textContent = '';
Actually the last one could be the fastest and more effective/efficient solution.
.textContent
is more efficient than .innerText
and .innerHTML
, see: MDN
The easiest way:
let container = document.getElementById("containerId");
container.innerHTML = "";
simply only IE:
parentElement.removeNode(true);
true
- means to do deep removal - which means that all child are also removed
simple and fast using for loop!!
var myNode = document.getElementById("foo");
for(var i = myNode.childNodes.length - 1; i >= 0; --i) {
myNode.removeChild(myNode.childNodes[i]);
}
this will not work in <span>
tag!
var myNode = document.getElementById("foo");
var fc = myNode.firstChild;
while( fc ) {
myNode.removeChild( fc );
fc = myNode.firstChild;
}
If there's any chance that you have jQuery affected descendants, then you must use some method that will clean up jQuery data.
$('#foo').empty();
The jQuery .empty() method will ensure that any data that jQuery associated with elements being removed will be cleaned up.
If you simply use DOM
methods of removing the children, that data will remain.
Functional only approach:
const domChildren = (el) => Array.from(el.childNodes)
const domRemove = (el) => el.parentNode.removeChild(el)
const domEmpty = (el) => domChildren(el).map(domRemove)
"childNodes" in domChildren will give a nodeList of the immediate children elements, which is empty when none are found. In order to map over the nodeList, domChildren converts it to array. domEmpty maps a function domRemove over all elements which removes it.
Example usage:
domEmpty(document.body)
removes all children from the body element.