Remove all child elements of a DOM node in JavaScript

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

    i saw people doing:

    while (el.firstNode) {
        el.removeChild(el.firstNode);
    }
    

    then someone said using el.lastNode is faster

    however I would think that this is the fastest:

    var children = el.childNodes;
    for (var i=children.length - 1; i>-1; i--) {
        el.removeNode(children[i]);
    }
    

    what do you think?

    ps: this topic was a life saver for me. my firefox addon got rejected cuz i used innerHTML. Its been a habit for a long time. then i foudn this. and i actually noticed a speed difference. on load the innerhtml took awhile to update, however going by addElement its instant!

提交回复
热议问题