JavaScript’s Node.removeChild()
method removes a child node from the Node
.
Syntax
Node.removeChild(parameter);
Parameters
A child node to remove from the node.
Return value
The removed node.
Exceptions
NotFoundError
DOMException
Thrown if the child node is not a child of the parent node.
Examples
Here are some examples of using the JavaScript removeChild()
method.
Suppose we have the following unordered list from which we would like to remove the last li
element:
<ul id="menu">
<li>Home</li>
<li>Blog</li>
<li>Contact Me</li>
</ul>
How can we do that?
We can select the ul
element with the getElementById()
method and use the removeChild()
method remove its last child element:
let menu = document.getElementById('menu');
menu.removeChild(menu.lastElementChild);
The lastElementChild
property returns the last child element of the ul
element.
Now our HTML looks like this:
<ul id="menu">
<li>Home</li>
<li>Blog</li>
</ul>
What if we wanted to remove all the li
elements from the menu?
We could use a simple while
loop and the removeChild()
method:
let menu = document.getElementById('menu');
while (menu.firstElementChild) {
menu.remove(menu.firstElementChild);
}
The firstElementChild
property returns the first child element of the ul
element and can be used here as an alternative to the lastElementChild
property.
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
removeChild() |
1 | 12 | 1 | 5 | 7 | 1.1 | 18 | 4 | 10.1 | 1 | 1.0 | 4.4 |