Remove all child elements of a DOM node in JavaScript

前端 未结 30 1861
花落未央
花落未央 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 03:58

    Generally, JavaScript uses arrays to reference lists of DOM nodes. So, this will work nicely if you have an interest in doing it through the HTMLElements array. Also, worth noting, because I am using an array reference instead of JavaScript proto's this should work in any browser, including IE.

    while(nodeArray.length !== 0) {
      nodeArray[0].parentNode.removeChild(nodeArray[0]);
    }
    

提交回复
热议问题