removeChild
removeChild() works similar to appendChild() except that we are removing as opposed to adding a child element. When using appendChild, we are adding a new element to an existing parent element and removeChild works the same way. We are not just creating a NEW element on the webpage, we are removing a child element from an existing parent element.
Let's create an unordered list to demonstrate:
This is an unordered List [ul]
- Item One
- Item Two
- Item Three
- Sub-Item One
- Sub-Item Two
- Item Four
- Item Five
and in an unordered List [ul], all of [li]'s are children of the parent [ul] element.
1. first off, we need to define the child element we want to remove, in this example we are going to remove Item Two from the list:- const remItem = document.querySelectorAll('li')[1];
- selects the 2nd list item [Item Two]
- const unordList = remItem.parentElement;
- selects the parent element for remItem, which is the [ul] unordered list element
- unordList.removeChild(remItem);
- removes the line item [li], remItem from the parent unordered list [ul] unordList
and we are left with:
- Item One
- Item Two
- Item Three
- Sub-Item One
- Sub-Item Two
- Item Four
- Item Five
*note that you could also simplify the code by eliminating step 2, and changing step 3, like so:
- remItem.parentElement.removeChild(remItem);