Remove all child elements of a DOM node in JavaScript

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

    Ecma6 makes it easy and compact

    myNode.querySelectorAll('*').forEach( n => n.remove() );
    

    This answers the question, and removes “all child nodes”.

    If there are text nodes belonging to myNode they can’t be selected with CSS selectors, in this case we’ve to apply (also):

    myNode.textContent = '';
    

    Actually the last one could be the fastest and more effective/efficient solution.

    .textContent is more efficient than .innerText and .innerHTML, see: MDN

    0 讨论(0)
  • 2020-11-22 04:10

    The easiest way:

    let container = document.getElementById("containerId");
    container.innerHTML = "";
    
    0 讨论(0)
  • 2020-11-22 04:11

    simply only IE:

    parentElement.removeNode(true);
    

    true - means to do deep removal - which means that all child are also removed

    0 讨论(0)
  • 2020-11-22 04:11

    simple and fast using for loop!!

    var myNode = document.getElementById("foo");
    
        for(var i = myNode.childNodes.length - 1; i >= 0; --i) {
          myNode.removeChild(myNode.childNodes[i]);
        }
    

    this will not work in <span> tag!

    0 讨论(0)
  • 2020-11-22 04:12
    var myNode = document.getElementById("foo");
    var fc = myNode.firstChild;
    
    while( fc ) {
        myNode.removeChild( fc );
        fc = myNode.firstChild;
    }
    

    If there's any chance that you have jQuery affected descendants, then you must use some method that will clean up jQuery data.

    $('#foo').empty();
    

    The jQuery .empty() method will ensure that any data that jQuery associated with elements being removed will be cleaned up.

    If you simply use DOM methods of removing the children, that data will remain.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题