Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I remove a child node in HTML using JavaScript?
In JavaScript, you can remove child nodes from HTML elements using several methods. The most common approaches are removeChild() and the modern remove() method.
Using removeChild() Method
The removeChild() method removes a specified child node from its parent element. You need to call it on the parent element and pass the child node as a parameter.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Remove Child Node</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
color: green;
}
</style>
</head>
<body>
<h1>Removing a child node using removeChild()</h1>
<div class="result">
<ul class="animal">
<li>Cow</li>
<li>Lion</li>
<li>Tiger</li>
<li>Buffalo</li>
</ul>
</div>
<button class="btn">Remove First Item</button>
<script>
let animalList = document.querySelector(".animal");
document.querySelector(".btn").addEventListener("click", () => {
if (animalList.children.length > 0) {
animalList.removeChild(animalList.children[0]);
}
});
</script>
</body>
</html>
Using remove() Method (Modern Approach)
The remove() method is a simpler, modern way to remove an element directly without needing to access its parent.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Remove Node</title>
</head>
<body>
<ul id="fruits">
<li>Apple</li>
<li>Banana</li>
<li>Orange</li>
</ul>
<button onclick="removeLastItem()">Remove Last Item</button>
<script>
function removeLastItem() {
const fruitList = document.getElementById("fruits");
if (fruitList.lastElementChild) {
fruitList.lastElementChild.remove();
}
}
</script>
</body>
</html>
Comparison of Methods
| Method | Syntax | Browser Support | Ease of Use |
|---|---|---|---|
removeChild() |
parent.removeChild(child) |
All browsers | Requires parent reference |
remove() |
element.remove() |
Modern browsers | Direct removal |
Key Points
- Always check if the child node exists before removing to avoid errors
- Use
childrenproperty instead ofchildNodesto avoid text nodes -
remove()is cleaner butremoveChild()has better browser compatibility - Both methods permanently remove the element from the DOM
Conclusion
Use remove() for modern applications and removeChild() for legacy browser support. Always validate that the element exists before attempting removal to prevent errors.
Advertisements
