I'm trying to implement a piece of code in javascript which removes all child nodes inside a div in such a way it is empty after the execution of the code. I was thinking of using a while
loop and the hasChildNodes()
method applied to this div, and inside the argument of the loop insert a line of code which removes the first-child of this div in each check until it removes all child Nodes, but I find it quite cumbersome. Is there a faster way to get rid of all elements inside a div using some kind of method?
How can I delete all Child Nodes inside a div in one shot in such a way it is empty after that code lines are executed using javascript?
464 views Asked by Julio Rodriguez At
3
There are 3 answers
0
On
One option if you don't using any libraries like jQuery, dojo or using SVG or events on child nodes:
var node = document.getElementById("foo");
node.innerHTML = "";
If you are using a library like dojo or jQuery, then you will to avoid memory leaks, because references to child nodes from javascript are not cleared, so the dom node is never freed.
Always use the appropriate library method to clear the DOM so that it can release event registrations, node references e.g. jQuery: api.jquery.com/empty
0
On
If you intend to clear the div with child nodes and text, you can set its innerHTML to empty text.
var target = document.getElementById("target");
setTimeout(function() {
target.innerHTML = "";
},3000);
The text below will disappear after three seconds.
<div id="target">
Some text.
<div>
Some text inside a child node.
</div>
</div>
Jquery's $.html() method.
like so:
all child elements inside will be replaced with '';
or