How to use removeChild() In Javascript

In this approach, we are using the HTML DOM removeChild() method, which will remove a specified child node of the given element. We select an element by the use of the querySelector getting the last element of that selected element and removing that with the help of the removeChild() method.

Example: This example shows the implementation of the above-explained approach.

html




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
    content="width=device-width,
                initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible"
    content="ie=edge">
 
    <title>Document</title>
</head>
 
<body>
    <ul>
        <li>Get Up in Morning</li>
        <li>Do some exercise</li>
        <li>Get Ready for school</li>
        <li>Study Daily</li>
        <li>Do homework</li>
    </ul>
    <input id="btn" type="button"
    value="Remove Childrens">
</body>
<script>
    function deleteChild() {
        let e = document.querySelector("ul");
 
        //e.firstElementChild can be used.
        let child = e.lastElementChild;
        while (child) {
            e.removeChild(child);
            child = e.lastElementChild;
        }
    }
    let btn = document.getElementById(
        "btn").onclick = function () {
            deleteChild();
        }
</script>
 
</html>


Output:

Output

Remove all the child elements of a DOM node in JavaScript

Child elements are the nested elements in the HTML and we have to remove them. To remove the elements in HTML we need to use DOM methods.

There are so many ways to remove the child elements of a DOM node:

Table of Content

  • Using removeChild()
  • Using innerHTML property

Similar Reads

Using removeChild()

In this approach, we are using the HTML DOM removeChild() method, which will remove a specified child node of the given element. We select an element by the use of the querySelector getting the last element of that selected element and removing that with the help of the removeChild() method....

Using innerHTML property

...