<div id='test'></div>
var el = document.getElementById('test');
for (let i = 0; i < 1000; ++i) el.appendChild(document.createElement('div'));
let node = document.getElementById('test');
node.textContent = '';
let node = document.getElementById('test');
while(node.firstChild) { node.removeChild(node.firstChild); }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
textContent | |
removeChild |
Test name | Executions per second |
---|---|
textContent | 1558586.5 Ops/sec |
removeChild | 2125881.2 Ops/sec |
This benchmark compares two methods for removing all child nodes from a pre-existing HTML element:
Method 1: textContent
: This method sets the textContent
property of the node to an empty string, effectively clearing all its child content.
Method 2: removeChild
Loop: This method iterates through each child node of the element and removes it individually using the removeChild
method.
Pros and Cons:
textContent
:
removeChild
Loop:
removeChild
. More verbose syntax.Other Considerations:
removeChild
loop is slightly faster on average (though the difference isn't huge). This can vary depending on factors like browser, HTML structure, and node count.Alternatives:
textContent
approach with an empty string or null
.