Remove all child elements of a DOM node in JavaScript

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

    Functional only approach:

    const domChildren = (el) => Array.from(el.childNodes)
    const domRemove = (el) => el.parentNode.removeChild(el)
    const domEmpty = (el) => domChildren(el).map(domRemove)
    

    "childNodes" in domChildren will give a nodeList of the immediate children elements, which is empty when none are found. In order to map over the nodeList, domChildren converts it to array. domEmpty maps a function domRemove over all elements which removes it.

    Example usage:

    domEmpty(document.body)
    

    removes all children from the body element.

提交回复
热议问题