Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all child nodes of a node

I have a node of DOM document. How can I remove all of its child nodes? For example:

<employee> 
     <one/>
     <two/>
     <three/>
 </employee>

Becomes:

   <employee>
   </employee>

I want to remove all child nodes of employee.

like image 685
akshay Avatar asked Jun 20 '11 13:06

akshay


People also ask

How do you clear all child nodes?

Child nodes can be removed from a parent with removeChild(), and a node itself can be removed with remove(). Another method to remove all child of a node is to set it's innerHTML=”” property, it is an empty string which produces the same output.

Will remove all child nodes of the set of matched elements from the DOM?

The empty() method removes all child nodes from the set of matched elements.


2 Answers

No need to remove child nodes of child nodes

public static void removeChilds(Node node) {
    while (node.hasChildNodes())
        node.removeChild(node.getFirstChild());
}
like image 188
kop Avatar answered Sep 29 '22 19:09

kop


Just use:

Node result = node.cloneNode(false);

As document:

Node cloneNode(boolean deep)
deep - If true, recursively clone the subtree under the specified node; if false, clone only the node itself (and its attributes, if it is an Element).
like image 33
Google New Avatar answered Sep 29 '22 21:09

Google New