title: Recursively remove all nested nodes in javascript
body: <p>I've been trying to write something to remove all nodes within an element, including the nodes within those nodes. I feel like I've come pretty close with this</p>
  
  <pre><code>function clear(node) {
      var l = node.childNodes.length;
      for (var i = 0; i &lt; l; i++) {
          console.log(i, node.childNodes);
          var child = node.childNodes[i];
  
          if (!child.hasChildNodes()) {
              var newchild = child.parentNode;
              newchild.removeChild(child);
              console.log("removed" + child);
              clear(newchild);
          } else {
              clear(child);
          }
      }
  }
  </code></pre>
  
  <p>And the markup looks something like this</p>
  
  <pre><code>&lt;div&gt;
      &lt;canvas&gt;&lt;/canvas&gt;
      &lt;div id="diagbox"&gt;
          &lt;div id="diag_text"&gt;Here's some text&lt;/div&gt;
      &lt;/div&gt;
      &lt;ul id="option_ul"&gt;
          &lt;li&gt;Some text&lt;/li&gt;
          &lt;li&gt;Some text&lt;/li&gt;
      &lt;/ul&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>And this is how far it gets before failing:</p>
  
  <pre><code>&lt;div&gt;
      &lt;div id="diagbox"&gt;
          &lt;div id="diag_text"&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;ul id="option_ul"&gt;
      &lt;/ul&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>It removes the text node in diag_text, but fails to remove the actual div. It also removes the text nodes in the li elements, and for some reason succeeds to remove the li elements as well, but stops at the ul. The canvas is also succesfully removed, which is odd because it's top level and I was assuming that's why the others weren't working. The whole thing stops because at some point a TypeError occurs, "child is undefined".</p>
  
  <p>Not quite sure where I'm going wrong here</p>
  
  <p>EDIT:  Definitely should have specified: I'm wanting to go through and remove all of the nodes and not just the parents because the content of these elements are actually dynamically generated and need to be scrubbed for different use cases.</p>