Remove all child elements of a DOM node in JavaScript?

Answer

An earlier edit to this answer used 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).
The loop continues to check for 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);
}
}
<div id='foo' style="height: 100px; width: 100px; border: 1px solid black;">
<span>Hello</span>
</div>
<button id='doFoo'>Remove via lastChild-loop</button>

 

All node.js Questions

Ask your interview questions on node-js

Write Your comment or Questions if you want the answers on node-js from node-js Experts
Name* :
Email Id* :
Mob no* :
Question
Or
Comment* :
 





Disclimer: PCDS.CO.IN not responsible for any content, information, data or any feature of website. If you are using this website then its your own responsibility to understand the content of the website

--------- Tutorials ---