0

here is the html part ..

var removeButton = document.getElementById("remove");
removeButton.addEventListener("click", removeItem);

function removeItem() {
  var list = document.getElementById("list");
  var listItems = list.getElementsByTagName("li");
  var last = listItems[listItems.length - 1];
  list.removeChild(last);

  if (last == listItems.length - 1) {
    document.getElementById("remove").disabled = true;
  }
}
<ul id="list">
  <li class="abc">cold cereal</li>
  <li class="abc">Ice cream</li>
  <li class="abc">Honey</li>
  <li class="abc">Olive Oil</li>
</ul>
<button id="btn" onclick="myfun()">add item</button>
<button id="remove">remove item</button>

clicked on the remove button and its removing the items from the list after all the items are deleted from the list its showing the error .

enter image description here

when i run this code every thing is working fine but when all the items are deleted from the list after deleting all the list items from the list when i press the button once more it shows the error

Phil
  • 157,677
  • 23
  • 242
  • 245
fazal
  • 43
  • 7
  • Welcome to Stackoverflow, but please remember to [put in the effort to write a good post](/help/how-to-ask) if you want to get good answers. – Mike 'Pomax' Kamermans Oct 07 '21 at 03:58
  • What do you think `listItems[listItems.length - 1]` will return when `listItems` is empty? Also, `last == listItems.length - 1` will **never** be `true` since `last` is not a number – Phil Oct 07 '21 at 04:18

3 Answers3

1

this way

const 
  removeButton = document.getElementById('remove') 
, list         = document.getElementById('list')
  ;
removeButton.addEventListener("click", removeItem);

function removeItem()
  {
  let
    listItems = list.querySelectorAll('li')
  , lastRef   = listItems.length - 1
    ;
  list.removeChild(listItems[lastRef] );

  if (lastRef === 0) {
    removeButton.disabled = true;
  }
}
<ul id="list">
  <li class="abc">cold cereal</li>
  <li class="abc">Ice cream</li>
  <li class="abc">Honey</li>
  <li class="abc">Olive Oil</li>
</ul>
<button id="btn" onclick="myfun()">add item</button>
<button id="remove">remove last item</button>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
0

When your all nodes are deleted then you can't perform delete operation you will have to apply a condition to overcome this

Replace your removeItem function code with the given below-

function removeItem() {
    var list = document.getElementById("list");
    var listItems = list.getElementsByTagName("li");
    if (listItems.length > 0) {
      var last = listItems[listItems.length - 1];
      list.removeChild(last);
    }
    else{
      alert("can't delete")
    }
  }
Gulshan Aggarwal
  • 954
  • 1
  • 7
  • 13
0

i don't know why you used this

if( last == listItem.length - 1)
{
document.getElementById('remove').disable = true;
}

try this

if(listItem.length - 1 === 0){
        document.getElementById("remove").disabled = true;
    }
}