Tutorials using JS
Remove last item from list
Given a list element in the HTML document, remove the last item element from the list element, using JavaScript
Solution
To remove the last item from the given list element in the document, use Element.removeChild()
method. Call removeChild()
method on the list element, and pass the last list-item as argument to the method.
//get the list element
const list = document.getElementById("myList");
//remove the last list-item
list.removeChild(list.lastElementChild);
Program
In the following HTML code, we have a list element #myList
. When user clicks on the button Click Me
, we will remove the last list-item <li>cherry</li>
from the list element.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Remove last list-item from list element</h2>
<button id="myBtn">Click me</button><br>
<ul id="myList">
<li>apple</li>
<li>banana</li>
<li>cherry</li>
</ul>
<script>
//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
//get the list element
const myList = document.getElementById("myList");
//remove last list-item from list element
myList.removeChild(myList.lastElementChild);
});
</script>
</body>
</html>