Q:

Can't remove all childNodes

I want to remove all childNodes with class="child" from their parentNode, but only odd sequence is removed. How can I remove all elements with class="child" in native javascript and why only odd sequence is removed?

var child = document.getElementsByClassName("child");

function remove(){
  for (var i=0; i<child.length; i++) {
    child[i].parentNode.removeChild(child[i]);
  }
}
document.getElementById("del").onclick = remove;
<div>
  <div class="child">
    Child 1
  </div>
  <div class="child">
    Child 2
  </div>
  <div class="child">
    Child 3
  </div>
  <div class="child">
    Child 4
  </div>
</div>

<br/>

<div>
  <div class="child">
    Child 5
  </div>
  <div class="child">
    Child 6
  </div>
</div>

<button id="del">Remove Child</button>

A:

getElementsByClassName() returns a NodeList, which is an array-like object that presents a live view of the results.
As you remove the class from those elements, the elements are removed from the NodeList.
When you remove the class from child[0], child shrinks, and child[0] becomes the next element.
There are a number of ways to fix this:

Copy the NodeList to an array so that it doesn't change underneath you (eg, child = Array.prototype.slice.call(child))
Loop backwards so you aren't affected by the changing indices
Always remove the class from child[0] until the NodeList is empty.

