How would I go about removing all of the child elements of a DOM node in JavaScript?
Say I have the following (ugly) HTML:
&
innerHTML.doFoo.onclick = () => {
const myNode = document.getElementById("foo");
myNode.innerHTML = '';
}
Hello
textContent.textContent. According to MDN this will be faster than innerHTML as browsers won't invoke their HTML parsers and will instead immediately replace all children of the element with a single #text node.doFoo.onclick = () => {
const myNode = document.getElementById("foo");
myNode.textContent = '';
}
Hello
lastChild:firstChild, but this is updated to use lastChild as in computer-science, in general, it's significantly faster to remove the last element of a collection than it is to remove the first element (depending on how the collection is implemented).firstChild just in case it's faster to check for firstChild than lastChild (e.g. if the element list is implemented as a directed linked-list by the UA).doFoo.onclick = () => {
const myNode = document.getElementById("foo");
while (myNode.firstChild) {
myNode.removeChild(myNode.lastChild);
}
}
Hello
lastElementChild:Element (namely #text nodes and ) children of the parent (but not their descendants) - and this may be desirable in your application (e.g. some templating systems that use inline HTML comments to store template instructions).lastElementChild in IE9.doFoo.onclick = () => {
const myNode = document.getElementById("foo");
while (myNode.lastElementChild) {
myNode.removeChild(myNode.lastElementChild);
}
}
Hello
Element.clearChildren monkey-patch:Element prototype in JavaScript to simplify invoking it to just el.clearChildren() (where el is any HTML element object).if( typeof Element.prototype.clearChildren === 'undefined' ) {
Object.defineProperty(Element.prototype, 'clearChildren', {
configurable: true,
enumerable: false,
value: function() {
while(this.firstChild) this.removeChild(this.lastChild);
}
});
}
Hello