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>
example: remove the first element from a list.
<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>
example: if a list has child nodes, remove the first (index: 0).
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>
example: remove an element from its parent and insert it again.
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>