fazal
fazal

Reputation: 63

This code is working but after working Why this code is showing error

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

Upvotes: 0

Views: 73

Answers (3)

Mister Jojo
Mister Jojo

Reputation: 22320

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>

Upvotes: 1

AbHisheK ThaKur
AbHisheK ThaKur

Reputation: 81

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;
    }
}

Upvotes: 0

Gulshan Aggarwal
Gulshan Aggarwal

Reputation: 999

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")
    }
  }

Upvotes: 0

Related Questions