Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dom
communitycreator

What is the DOM removeChild() method?

Ayush Trivedi

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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.

RELATED TAGS

dom
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring