Remove all child elements of a DOM node in JavaScript

前端 未结 30 1405
花落未央
花落未央 2020-11-22 03:28

How would I go about removing all of the child elements of a DOM node in JavaScript?

Say I have the following (ugly) HTML:

&

30条回答
  •  灰色年华
    2020-11-22 04:09

    element.innerHTML = "" (or .textContent) is by far the fastest solution

    Most of the answers here are based on flawed tests

    For example: https://jsperf.com/innerhtml-vs-removechild/15
    This test does not add new children to the element between each iteration. The first iteration will remove the element's contents, and every other iteration will then do nothing. In this case, while (box.lastChild) box.removeChild(box.lastChild) was faster because box.lastChild was null 99% of the time

    Here is a proper test: https://jsperf.com/innerhtml-conspiracy

    Finally, do not use node.parentNode.replaceChild(node.cloneNode(false), node). This will replace the node with a copy of itself without its children. However, this does not preserve event listeners and breaks any other references to the node.

提交回复
热议问题