Tutorials using JS
Remove first item from List
Given a list element in HTML document, remove the first item from the list element, using JavaScript
Solution
To remove the first list-item from the given list element in the document, use Element.removeChild()
method. Call removeChild()
method on the list element, and pass the first list-item as argument to the method.
//get the list element
const list = document.getElementById("myList");
//remove the first list-item
list.removeChild(list.firstElementChild);
Program
In the following HTML code, we have a list element #myList
. When user clicks on the button Click Me
, we will remove the first list-item <li>apple</li>
from the list element.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<h2>Remove first 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 first list-item from list element
myList.removeChild(myList.firstElementChild);
});
</script>
</body>
</html>