Remove all child elements of a DOM node in JavaScript

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

    You can remove all child elements from a container like below:

    function emptyDom(selector){
     const elem = document.querySelector(selector);
     if(elem) elem.innerHTML = "";
    }
    

    Now you can call the function and pass the selector like below:

    If element has id = foo

    emptyDom('#foo');
    

    If element has class = foo

    emptyDom('.foo');
    

    if element has tag = <div>

    emptyDom('div')
    

提交回复
热议问题