Code Result

How can I remove all child elements of a DOM node in JavaScript?

Suppose you are building a web app that manages the data of daily tasks, the user inserts the task and a list of tasks gets formed. But at some point in time, the user wants to remove all the tasks from the list and wants to make the list empty. So, as a developer, you should know how to remove all the child elements from the DOM node.

Читайте также:  login here

To remove all the elements from the DOM node we have the following approaches.

  • By iterating the DOM nodes and using the removeChild method.
  • By Erasing the innerHTML value to a blank string.
  • By using jQuery’s empty() method.
  • Using the replaceChildren() method.

By iterating the DOM nodes and using the removeChild Method

In this method, we will iterate the DOM using the while loop or for loop. At every iteration, we will check if there is an element remaining in the node using the nodeObject.hasChildNodes() method or nodeObject.childElementCount property, If there is any element present in the node we simple remove that using the nodeObject.removeChild() Method and pass the first node as an argument.

Syntax

parentElement.hasChildNodes() parentElement.removeChild(parentElement.firstChild)

Here the parentElement.hasChildNodes() will check if there is any element present in the DOM node or not. The parentElement.removeChild(parentElement.firstChild) remove the first child of the DOM node.

Algorithm

  • STEP 1 − Iterate over all the DOM nodes. To iterate all the nodes, you could use any loop such as for or while loop.
  • STEP 2 − At every iteration we checked if there is any child present in the parent or not.
  • STEP 3 − If there is any child we remove it using the removeChild( ) method.

Example 1

Removing all child elements using reomveChild() method

In the example below, we remove all child elements of a DOM node using removeChild() method. We use while loop to iterate all child nodes. First we check if the child element exists using hasChildNodes() method.

     

Removing All Child Elements using removeChild() Method

Click "Remove Child" to remove all child button elements.




Example 2

Removing all child elements using nodeObject.remove() method

Читайте также:  Cpp pass by reference

In the example below, we remove all child elements of a DOM node using nodeObject.remove()method. We use while loop to iterate all child nodes. First we check if the child element exists using hasChildNodes() method.

   

Removing All Child Elements using remove() Method

Click "Remove Child" to remove all child button elements.




By erasing the innerHTML value:

In this method, we assign a blank string or null to object.innerHTML . Although this approach seems easy, there are some disadvantages too. The first one is, that if there is SVG inside the parent it won’t remove that. The second is, that it is considered very slow because when you assign a null or empty string to innerHTML, the DOM gets removed from the surface but the browser persists the child elements which makes the overall performance slow.

Syntax

parent.innerHTML = null or parent.innerHTML = ""

Here the parent is the parent DOM node from which we want to remove the child elements.

Example

  

Removing All Child Elements by assigning parent.innerHTML value to null

Click "Remove Child" to remove all child button elements.




By using the jQuery’s empty() Method

The empty() method of jQuery removes all child nodes from a set of matched elements. We select out parent DOM element using and apply the empty() method on it.

Syntax

Example

  

Removing All Child Elements using jQuery’s empty() Method

Click "Remove Child" to remove all child button elements.




By using the replaceChildren() Method

The replaceChildren() method is used to replace the old elements of the DOM node with a newer set of elements. This method takes the node elements as arguments and replaces the DOM elements with the same order as arguments. If you do not enter any argument then it simply replaces the old elements with null, which means the old element gets removed.

Syntax

parentElement.replaceElement();

Here the parentElement is the DOM node from which we want to remove chid elements.

Example

  

Removing All Child Elements using replaceElement() Method

Click "Remove Child" to remove all child button elements.




We have discussed four methods to remove all child elements of a DOM node in JavaScript. You can use any of them for your convenience. We recommend you to use the first method or the fourth method. If you are using jQuery then use the third method, we won’t recommend you to use the second method if you are building a complex UI because it makes the web pages slower.

Источник

Node: removeChild() method

The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.

Note: As long as a reference is kept on the removed child, it still exists in memory, but is no longer part of the DOM. It can still be reused later in the code.

If the return value of removeChild() is not stored, and no other reference is kept, it will be automatically deleted from memory after a short time.

Unlike Node.cloneNode() the return value preserves the EventListener objects associated with it.

Syntax

Parameters

A Node that is the child node to be removed from the DOM.

Exception

Thrown if the child is not a child of the node.

Thrown if the child is null .

Examples

Simple examples

div id="top"> div id="nested">div> div> 

To remove a specified element when knowing its parent node:

let d = document.getElementById("top"); let d_nested = document.getElementById("nested"); let throwawayNode = d.removeChild(d_nested); 

To remove a specified element without having to specify its parent node:

let node = document.getElementById("nested"); if (node.parentNode)  node.parentNode.removeChild(node); > 

To remove all children from an element:

let element = document.getElementById("idOfParent"); while (element.firstChild)  element.removeChild(element.firstChild); > 

Causing a TypeError

let top = document.getElementById("top"); let nested = document.getElementById("nested"); // Throws Uncaught TypeError let garbage = top.removeChild(nested); 

Causing a NotFoundError

div id="top"> div id="nested">div> div> 
let top = document.getElementById("top"); let nested = document.getElementById("nested"); // This first call correctly removes the node let garbage = top.removeChild(nested); // Throws NotFoundError garbage = top.removeChild(nested); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

HTML DOM Element removeChild()

If a list has child nodes, remove the first (index 0):

const list = document.getElementById(«myList»);

if (list.hasChildNodes()) list.removeChild(list.children[0]);
>

Remove all child nodes from a list:

const list = document.getElementById(«myList»);

while (list.hasChildNodes()) list.removeChild(list.firstChild);
>

Description

The removeChild() method removes an element’s child.

Note

The child is removed from the Document Object Model (the DOM).

However, the returned node can be modified and inserted back into the DOM (See «More Examples»).

See Also:

Syntax

Parameters

Return Value

More Examples

Remove an element from its parent node:

Example

Remove an element from its parent, and insert it again:

const element = document.getElementById(«myLI»);

function removeLi() element.parentNode.removeChild(element);
>
function appendLi() const list = document.getElementById(«myList»);
list.appendChild(element);
>

Note

Use appendChild() or insertBefore() to insert a removed node into the same document.

Use document.adoptNode() or document.importNode() to insert it into another document.

Example

Remove an element from its parent and insert it into another document:

const child = document.getElementById(«mySpan»);

function remove() child.parentNode.removeChild(child);
>

function insert() const frame = document.getElementsByTagName(«IFRAME»)[0]
const h = frame.contentWindow.document.getElementsByTagName(«H1»)[0];
const x = document.adoptNode(child);
h.appendChild(x);
>

Browser Support

element.removeChild() is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Источник

JavaScript — remove all child elements

Dollie-Rutledge

In this article, we would like to count different ways how to remove all child elements using JavaScript.

const element = document.querySelector('#element'); while(element.lastChild)
const element = document.querySelector('#element'); element.innerHTML = '';

Note: This solution is not recommended.

$('#element').empty(); // with jQuery

Explanation

DOM is composed with nodes that have different types. Element is one kind of node type that is able to contain different nodes inside. It is important to split problem of removing content for nodes removing and elements removing. More often it is necessary to remove all nodes. In this post different ways how to remove content starting from nodes removing are described (1-7 points).

1. removeChild() method examples

To use this approach it is necessary to have parent element that can be taken with parentNode property. To remove element removeChild() or remove() methods are useful. Second one is not supported by older browsers.

1.1. lastChild property

This approach removes all nodes.

// ONLINE-RUNNER:browser;    

Line 1

Line 2

Line 3

function emptyElement(element) < var child = element.lastChild; while(child) < element.removeChild(child); // or just: child.remove() child = element.lastChild; >> var element = document.querySelector('#element'); function onClick()

1.2. firstNode propert

This approach removes all nodes.

// ONLINE-RUNNER:browser;    

Line 1

Line 2

Line 3

function emptyElement(element) < var child = element.firstChild; while(child) < element.removeChild(child); // or just: child.remove() child = element.firstChild; >> var element = document.querySelector('#element'); function onClick()

1.3. childNodes property

This approach removes all nodes.

// ONLINE-RUNNER:browser;    

Line 1

Line 2

Line 3

function emptyElement(element) < var children = element.childNodes; while(children.length >0) < var child = children[children.length - 1]; // children[0]; element.removeChild(child); // or just: child.remove() >> var element = document.querySelector('#element'); function onClick()

3. innerHTML property example

This approach removes all nodes.

// ONLINE-RUNNER:browser;    

Line 1

Line 2

Line 3

var element = document.querySelector('#element'); function onClick()

4. innerText property example

This approach removes all nodes.

// ONLINE-RUNNER:browser;    

Line 1

Line 2

Line 3

var element = document.querySelector('#element'); function onClick()

5. textContent propert example

This approach removes all nodes.

// ONLINE-RUNNER:browser;    

Line 1

Line 2

Line 3

var element = document.querySelector('#element'); function onClick()

6. jQuery examples

This approach removes all nodes.

// ONLINE-RUNNER:browser;      

Line 1

Line 2

Line 3

7. Deleting selected range example

This approach removes all nodes.

// ONLINE-RUNNER:browser;    

Line 1

Line 2

Line 3

function emptyElement(element) < var range = new Range(); range.selectNodeContents(element); range.deleteContents(); >var element = document.querySelector('#element'); function onClick()

8. children property example

Importan note: this approach removes only elements placed directly in the div#element.

// ONLINE-RUNNER:browser;    

Line 1

Line 2

Line 3

Hints

It is possible to check if element is empty with hasChildNodes() method.

Alternative titles

  1. JavaScript — remove all nodes from DOM node
  2. JavaScript — empty DOM element
  3. JavaScript — clear HTML node
  4. JavaScript — clear HTML element (container element)
  5. JavaScript — clear element (container element)
  6. JavaScript — empty element (container element)
  7. JavaScript — empty HTML node
  8. JavaScript — empty DOM node
  9. JavaScript — clean HTML node
  10. JavaScript — clean HTML element (container element)
  11. JavaScript — clean element (container element)
  12. JavaScript — remove all children elements of HTML element

Источник

Оцените статью