How to remove all child elements of a DOM node in JavaScript?
I have the following HTML structure:
<p id="foo">
<span>hello</span>
<div>world</div>
</p>
And I’ve selected the node using:
var myNode = document.getElementById("foo");
What is the proper way to remove all child elements from this DOM node so that only <p id="foo"></p> remains?
I’ve considered setting myNode.childNodes = new Array(); but I’m not sure if this is the correct approach. Should I be using a combination of removeElement or another method?
Please provide both vanilla JavaScript and jQuery solutions if possible.
To remove all child elements from a DOM node in JavaScript, you have several effective approaches. The most common methods include using removeChild() in a loop, setting innerHTML to an empty string, or using modern remove() methods. For your specific case with the <p id="foo"> element, any of these methods will successfully remove the <span> and <div> elements while leaving the parent paragraph element intact.
Contents
- Common Methods for Removing Child Elements
- Method 1: Using removeChild() with a Loop
- Method 2: Setting innerHTML to Empty String
- Method 3: Using remove() on Each Child
- Method 4: Using jQuery’s empty() Method
- Performance and Browser Compatibility Comparison
- Complete Working Examples
- Best Practices and Recommendations
Common Methods for Removing Child Elements
When working with DOM manipulation in JavaScript, removing all child elements from a node is a common task. Based on the research findings, there are several approaches you can take, each with its own advantages and considerations.
The method you considered - myNode.childNodes = new Array() - is not correct because the childNodes property is read-only and cannot be directly assigned to. Instead, you need to use the proper DOM manipulation methods.
Method 1: Using removeChild() with a Loop
This is the traditional approach that works across all browsers and is commonly recommended by GeeksforGeeks.
var myNode = document.getElementById("foo");
// Remove all child elements
while (myNode.lastChild) {
myNode.removeChild(myNode.lastChild);
}
How it works:
- The loop continues as long as there’s a
lastChild - Each iteration removes the last child from the parent
- This approach is efficient because it works with the live DOM collection
- It handles both element nodes and text nodes
Alternative implementation using firstChild:
var myNode = document.getElementById("foo");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
Method 2: Setting innerHTML to Empty String
This is often the simplest and fastest method, as noted in the GeeksforGeeks documentation.
var myNode = document.getElementById("foo");
myNode.innerHTML = "";
Advantages:
- Very concise and easy to understand
- Typically faster than looping
- Works in all modern browsers
Considerations:
- This approach removes all content including text nodes, comments, etc.
- It clears the entire inner content, not just element nodes
- In some cases, it might be slightly less performant for very large DOM structures
Method 3: Using remove() on Each Child
This modern approach uses the remove() method which is supported in all modern browsers.
var myNode = document.getElementById("foo");
// Convert HTMLCollection to array and remove each child
Array.from(myNode.children).forEach(child => child.remove());
How it works:
myNode.childrenreturns a live HTMLCollection of element children onlyArray.from()converts the collection to an arrayforEach()iterates over each child and callsremove()on it
Alternative using while loop with remove():
var myNode = document.getElementById("foo");
while (myNode.firstChild) {
myNode.firstChild.remove();
}
Method 4: Using jQuery’s empty() Method
If you’re using jQuery in your project, the empty() method provides a simple solution.
$("#foo").empty();
How it works:
- jQuery’s
empty()method removes all child nodes and content from the selected element - It’s equivalent to setting
innerHTML = ""but with jQuery’s cross-browser consistency - The method returns the jQuery object for chaining
Example with jQuery:
// Using jQuery
$("#foo").empty();
// Alternative jQuery approach
$("#foo").html("");
Performance and Browser Compatibility Comparison
| Method | Browser Compatibility | Performance | Notes |
|---|---|---|---|
removeChild() loop |
All browsers | Good | Most compatible, handles all node types |
innerHTML = "" |
All browsers | Excellent | Fastest and simplest |
remove() on children |
Modern browsers | Good | Clean syntax, elements only |
jQuery empty() |
jQuery-supported browsers | Good | Consistent across browsers |
According to SQLpey’s research, the innerHTML approach is generally the fastest, while the removeChild() loop offers the best compatibility.
Complete Working Examples
Here are complete HTML examples demonstrating each method:
Example 1: removeChild() Loop Method
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>removeChild() Example</title>
</head>
<body>
<p id="foo">
<span>hello</span>
<div>world</div>
</p>
<button onclick="removeChildren()">Remove Children</button>
<script>
function removeChildren() {
var myNode = document.getElementById("foo");
while (myNode.lastChild) {
myNode.removeChild(myNode.lastChild);
}
}
</script>
</body>
</html>
Example 2: innerHTML Method
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>innerHTML Example</title>
</head>
<body>
<p id="foo">
<span>hello</span>
<div>world</div>
</p>
<button onclick="clearChildren()">Clear Children</button>
<script>
function clearChildren() {
var myNode = document.getElementById("foo");
myNode.innerHTML = "";
}
</script>
</body>
</html>
Example 3: Modern remove() Method
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Modern remove() Example</title>
</head>
<body>
<p id="foo">
<span>hello</span>
<div>world</div>
</p>
<button onclick="removeChildElements()">Remove Child Elements</button>
<script>
function removeChildElements() {
var myNode = document.getElementById("foo");
Array.from(myNode.children).forEach(child => child.remove());
}
</script>
</body>
</html>
Example 4: jQuery empty() Method
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery empty() Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<p id="foo">
<span>hello</span>
<div>world</div>
</p>
<button onclick="jQueryClearChildren()">Clear Children with jQuery</button>
<script>
function jQueryClearChildren() {
$("#foo").empty();
}
</script>
</body>
</html>
Best Practices and Recommendations
When to Use Each Method:
-
Use
innerHTML = ""when:- You need the fastest performance
- You’re working with modern browsers
- You want the simplest code
- You need to remove all content (text, elements, comments, etc.)
-
Use
removeChild()loop when:- You need maximum browser compatibility
- You need to selectively remove nodes based on node type
- You’re working with legacy browsers
- You need more control over the removal process
-
Use
remove()on children when:- You’re targeting modern browsers only
- You want clean, readable code
- You only need to remove element nodes (not text or comments)
-
Use jQuery
empty()when:- You’re already using jQuery in your project
- You need consistent behavior across browsers
- You prefer jQuery’s syntax and chaining capabilities
Additional Considerations:
- Memory Management: All these methods properly clean up references to removed nodes, allowing garbage collection
- Event Handlers: When elements are removed, any event handlers attached to them are automatically cleaned up
- Performance Impact: For very large DOM structures, consider the performance implications of each method
- Live Collections: Be aware that
childNodesandchildrenare live collections, which can affect loop behavior
According to JavaScript Tutorial, the removeChild() method is fundamental to DOM manipulation and understanding it is valuable even when using more modern approaches.
For your specific use case with the <p id="foo"> element, any of these methods will work effectively. I’d recommend the innerHTML = "" approach for its simplicity and performance, or the removeChild() loop if you need maximum compatibility.
Sources
- GeeksforGeeks - Remove all the child elements of a DOM node in JavaScript
- JavaScript Tutorial - JavaScript removeChild() By Practical Examples
- SQLpey - Top 5 Ways to Effectively Remove All Child Elements of a DOM Node in JavaScript
- CodeLucky - HTML Node removeChild() Method: Removing Child Nodes
- GeeksforGeeks - HTML DOM removeChild() Method
- SitePoint - Removing Useless Nodes From the DOM
- Luis Llamas - Insert and remove elements in the DOM with JavaScript
Conclusion
Removing all child elements from a DOM node in JavaScript is straightforward with several effective methods available. For your specific HTML structure, you can choose from:
innerHTML = ""for the simplest and fastest solutionremoveChild()loop for maximum compatibility and control- Modern
remove()methods for clean syntax in modern browsers - jQuery’s
empty()if you’re already using jQuery
Each method successfully leaves only the <p id="foo"></p> element while removing all child content. The choice depends on your specific needs regarding browser compatibility, performance requirements, and coding preferences. Remember that childNodes = new Array() is not a valid approach - always use the proper DOM manipulation methods instead.