What is the DOM removeChild() method?
Overview
In this shot, we will learn how to remove a child element from a parent element.
removeChild() is
a method that removes the child element from its parent. Apply this method to the parent element and pass the child element in the removeChild() as a parameter to remove the child element from its parent.
Parameters
The method only takes one parameter:
list.childNodes[0]: The child node reference.
Code
Let’s write a code to remove a list item from a list.
Explanation
-
Line 5: We have a
ulelement (unordered list) with 3li(list items) inside it. -
Line 7: We have a paragraph tag to display text.
-
Line 9: We write a button tag with the
change()function, which will be called when the user clicks on it. -
Line 12: We write the JavaScript code in the script tag. We define a
change()function that will be called when the user clicks the button from the HTML page. -
Line 13: We use
getElementById()to select theullist, pass the idlistin it, and store it in the variable. -
Line 14: We
removethe firstlinode in the list. To do that, we apply theremoveChild()method on thelistelement and pass the parameter. We only pass the child node of that element as a parameter.list.childNodes[0]will return the firstliof the list and remove it.
Output
When we click the button, the first li list item is removed from the list.