Reputation: 63
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 .
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
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
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
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