Removing Elements with JavaScript

For loop vs While loop - No innerHTML


For loop

<ul>
  <li>List item (0)</li>
  <li>List item (1)</li>
  <li>List item (2)</li>
  <li>List item (3)</li>
</ul>
var li = document.getElementsByTagName('li');

for (var i = 0, len = li.length; i < len; i++){
  
  // New JS remove Function
  li[i].remove();
  
  // Safer cross browser
  // Has to traverse by going up to the parent and removing the child
  // Which is itself, the li element.
  li[i].parentNode.removeChild(li[i]);
  
}

While Loop

<ul>
  <li>List item (0)</li>
  <li>List item (1)</li>
  <li>List item (2)</li>
  <li>List item (3)</li>
</ul>
var li = document.getElementsByTagName('li');

while (li.length > 0) {
  
  // New JS remove Function
  li[0].remove();
  
  // Safer cross browser
  // Has to traverse by going up to the parent and removing the child
  // Which is itself, the li element.
  li[0].parentNode.removeChild(li[0]);
  
}

What's happening here?

The for loop is working correctly.

Because every iteration removes an element, the element position of the remaining elements shifts.

When List item (0) is removed, List item (1) moves into List item (0)'s position.

The loop index continues to increment which means i is now = 1.

List item (2) was shifted into List item (1)'s position and it is removed.

// It's an HTML collection, and not technically an array but we can visualize it like an array.

// First Iteration ( i = 1 )
var li = [
  'List item 1', // [0]
  'List item 2', // [1]
  'List item 3', // [2]
]

// Second Iteration ( i = 2 )
var li = [
  'List item 1', // [0]
  'List item 3', // [1]
]

// i is now equal to the length of the li html collection and the loop stops running.

Because of the shift List item (1)'s position is now in position [0] it is not removed. The shift continues when the next element is removed which is why every second element is not removed.


The position of the elements are always equal to the number of elements.

While there is a first element [0], remove it.

// It's an HTML collection, and not technically an array but it's easier to visualize

// First Iteration ( 3 greater than 0 )
var li = [
  'List item 1', // [0]
  'List item 2', // [1]
  'List item 3', // [2]
]

// Second Iteration ( 2 greater than 0 )
var li = [
  'List item 2', // [0]
  'List item 3', // [1]
]

// Third Iteration ( 1 greater than 0 )
var li = [
  'List item 3', // [0]
]

// Fourth Iteration ( 0 = 0 )
var li = []