Recently, I came across the fascinating technique of working with HTML DOM elements called innerHTML
.
I'm curious - is it considered best practice to remove all child nodes before replacing content using innerHTML
? What actually happens to the previous subtree when a new assignment is made?
var removeChildNodes = function(node) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
};
var dynamicContentNode = document.getElementById('dynamic-content');
// Should we always do this step?
removeChildNodes(dynamicContentNode);
// Populate the new subtree of HTML DOM elements
dynamicContentNode.innerHtml = '<div><p>Hello there</p></div>';