Remove last item of a list using javascript

Viewed 4986

Hello I have a simple unordered list and I would like to remove the last item on click of a button. I read somewhere that pop(); will do this but I am having trouble getting it working.

Here is what I have so far:

<button id="remove">remove item</button>

<ul id="list">
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
</ul>

var listItems = document.getElementById("list").getElementsByTagName("li");
var removeButton = document.getElementById("remove");

removeButton.addEventListener("click", removeItem);

function removeItem() {
    listItems.pop();
}

Here is the error I'm getting:

Uncaught TypeError: listItems.pop is not a function at HTMLButtonElement.removeItem

Which is weird because when I type listItems in the console I am getting the correct array:

listItems (7) [li, li, li, li, li, li, li]

jsfiddle

Anyone have any suggestions? I dont need to use .pop() any method that works will be fine

2 Answers
Related