Remove all child elements of a DOM node in JavaScript

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

    In response to DanMan, Maarten and Matt. Cloning a node, to set the text is indeed a viable way in my results.

    // @param {node} node
    // @return {node} empty node
    function removeAllChildrenFromNode (node) {
      var shell;
      // do not copy the contents
      shell = node.cloneNode(false);
    
      if (node.parentNode) {
        node.parentNode.replaceChild(shell, node);
      }
    
      return shell;
    }
    
    // use as such
    var myNode = document.getElementById('foo');
    myNode = removeAllChildrenFromNode( myNode );
    

    Also this works for nodes not in the dom which return null when trying to access the parentNode. In addition, if you need to be safe a node is empty before adding content this is really helpful. Consider the use case underneath.

    // @param {node} node
    // @param {string|html} content
    // @return {node} node with content only
    function refreshContent (node, content) {
      var shell;
      // do not copy the contents
      shell = node.cloneNode(false);
    
      // use innerHTML or you preffered method
      // depending on what you need
      shell.innerHTML( content );
    
      if (node.parentNode) {
        node.parentNode.replaceChild(shell, node);
      }
    
      return shell;
    }
    
    // use as such
    var myNode = document.getElementById('foo');
    myNode = refreshContent( myNode );
    

    I find this method very useful when replacing a string inside an element, if you are not sure what the node will contain, instead of worrying how to clean up the mess, start out fresh.

提交回复
热议问题