revision:
The removeChild() method removes an element's child. The child is removed from the Document Object Model (the DOM). However, the returned node can be modified and inserted back into the DOM.
element.removeChild(node) node.removeChild(node)
Parameters:
node : required. The node (element) to remove.
<p>Click "Remove" to remove all child nodes of ul.</p> <button onclick="myFunction()">Remove</button> <ul id="myList"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> <script> function myFunction() { const list = document.getElementById("myList"); while (list.hasChildNodes()) { list.removeChild(list.firstChild); } } </script>
<div> <button onclick="myChild()">Remove</button> <ul id="myList"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> </div> <script> function myChild() { const list = document.getElementById("myList"); list.removeChild(list.firstElementChild); } </script>
Click "Remove" to remove the first child (index 0)
<p>Click "Remove" to remove the first child (index 0)</p> <button onclick="myChild1()">Remove</button> <ul id="myList1"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> </div> <script> function myChild1() { const list1 = document.getElementById("myList1"); if (list1.hasChildNodes()) { list1.removeChild(list1.children[0]); } } </script>
Click the buttons to remove and insert the li element from the ul element:
<div> <p>Click the buttons to remove and insert the li element from the ul element:</p> <button onclick="removeLi()">Remove</button> <button onclick="appendLi()">Insert</button> <ul id="myList2"> <li id="myLI">Coffee</li> </ul> </div> <script> const element = document.getElementById("myLI"); function removeLi() { element.parentNode.removeChild(element); } function appendLi() { const list = document.getElementById("myList2"); list.appendChild(element); } </script>