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.

Removing the list item using removeChild().

Explanation

  • Line 5: We have a ul element (unordered list) with 3 li(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 the ul list, pass the id list in it, and store it in the variable.

  • Line 14: We remove the first li node in the list. To do that, we apply the removeChild() method on the list element and pass the parameter. We only pass the child node of that element as a parameter. list.childNodes[0] will return the first li of the list and remove it.

Output

When we click the button, the first li list item is removed from the list.