The Node.removeChild() method removes HTML Element from the current page via the DOM. This article will show you how to use it.
It is the data structure which represents every HTML tag present on a page – everything from the root <html> element that wraps the page to every <div>, <p>, <input>, and <span> – everything on the page is represented in the DOM, both its content and its structure.
Each HTML element is represented in the DOM as a Node – an abstraction of the on-page element.
Removing Elements From the DOM
removeChild() Method Syntax
- NODE is the node you wish to remove a child element from
- CHILD is the child element you wish to remove from NODE
- The return value of removeChild() is the removed CHILD Node
- If the return value is not used elsewhere or immediately assigned to a variable, it will be deleted
Removing Elements using removeChild() – Examples
To use the removeChild() method, we must first have an HTML Element (which will be represented in the DOM) to work with. A list is a good example, as items can be removed using removeChild():
<ul id="my-list"> <li>List item 1</li> <li id="remove-me">List item 2</li> </ul>
Above, a simple HTML list is created with the id of my-list.
var myList = document.getElementById('my-list'); var removeMe = document.createElement('remove-me'); myList.removeChild(removeMe);
First, the existing list in the HTML DOM is retrieved using getElementById().
Finally, removeChild() can be used to remove the element with the id remove-me from the existing list my-list.
It is also possible to use removeChild without knowing the details of the parent element:
var removeMe = document.getElementById('remove-me'); removeMe.parentNode.removeChild(node);
Above, the parentElement() method used to access the parent of the element to be removed, so that removeChild() can be called on it.
To add a child element instead of removing it, use appendChild() instead.