Remove all child elements of a DOM node in JavaScript

前端 未结 30 1412
花落未央
花落未央 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:07

    The currently accepted answer is wrong about innerHTML being slower (at least in IE and Chrome), as m93a correctly mentioned.

    Chrome and FF are dramatically faster using this method (which will destroy attached jquery data):

    var cNode = node.cloneNode(false);
    node.parentNode.replaceChild(cNode, node);
    

    in a distant second for FF and Chrome, and fastest in IE:

    node.innerHTML = '';
    

    InnerHTML won't destroy your event handlers or break jquery references, it's also recommended as a solution here: https://developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML.

    The fastest DOM manipulation method (still slower than the previous two) is the Range removal, but ranges aren't supported until IE9.

    var range = document.createRange();
    range.selectNodeContents(node);
    range.deleteContents();
    

    The other methods mentioned seem to be comparable, but a lot slower than innerHTML, except for the outlier, jquery (1.1.1 and 3.1.1), which is considerably slower than anything else:

    $(node).empty();
    

    Evidence here:

    http://jsperf.com/innerhtml-vs-removechild/167 http://jsperf.com/innerhtml-vs-removechild/300 https://jsperf.com/remove-all-child-elements-of-a-dom-node-in-javascript (New url for jsperf reboot because editing the old url isn't working)

    Jsperf's "per-test-loop" often gets understood as "per-iteration", and only the first iteration has nodes to remove so the results are meaningless, at time of posting there were tests in this thread set up incorrectly.

提交回复
热议问题