Skip to content Skip to sidebar Skip to footer

Removing LI From UL In For Loop (JS)

I'm trying to remove items from a list when a button is clicked. JSFiddle here - https://jsfiddle.net/y3u47f11/15/ HTML
  • 1

Solution 1:

The chlidren or childNodes is live element collection(HTMLCollection) so index may update after each remove, so remove the element at index 0. Although apply removeChild on parent node and add element as the argument.

window.emptyList = function () {
  var ul = document.querySelector('.list');
  var listLength = ul.children.length;

  for (i = 0; i < listLength; i++) {
    ul.removeChild(ul.children[0]);
  }
}
<ul class="list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

<a class="btn" onclick="emptyList()">clear list</a>

FYI : The childNodes includes the text nodes so use chlidren property instead.


Solution 2:

I think you need to do it in reverse order because when removing a node index no longer points to the correct node afterwards because the whole list has been reduced. Also, just query the li elements directly

window.emptyList = function () {
  var li = document.querySelectorAll('.list > li');
  var listLength = li.length;
  
  for (var i = listLength-1; i >=0 ; i--) {
    li[i].parentNode.removeChild(li[i]);   
  }
  
  // this works
  // ul.innerHTML = "";

}
<ul class="list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

<a class="btn" onclick="emptyList()">clear list</a>

Solution 3:

Try the below code. You are using removeChild wrong way.

window.emptyList = function () {
      var ul = document.querySelector('.list');
      var listLength = ul.children.length;

      for (i = 0; i < listLength; i++) {
        ul.removeChild(ul.childNodes[i]);
      }
    }

Solution 4:

window.emptyList = function () {
  var ul = document.querySelector('.list');
  var listLength = ul.children.length;

  while (ul.children.length !=0){
    ul.removeChild(ul.childNodes[0]);
  }

  // this works
  // ul.innerHTML = "";

}

the list length is altered once you remove the first one.


Post a Comment for "Removing LI From UL In For Loop (JS)"