DOM manipulation - moving a node

H

Ha

I am trying to move a node of a tree up one level.
Example: I want to move C to be a child of A, then remove B.

Before:
<A>
<B>
<C>
<D/>
<E/>
</C>
</B>
</A>

After:
<A>
<C>
<D/>
<E/>
</C>
</A>

Here's the code I'm using. For some reason the children do not get added.
What am I missing?


NodeList nodeListB = document.getElementsByTagName("B");
Node BNode = nodeListMsgsRs.item(0);
Node ANode = eventsMsgsRsNode.getParentNode();

//these are the children of <B>
NodeList childrenBNodes = BNode.getChildNodes();

//add all of the children of <>B to B's parent <A>
for(int i =0; i<childrenBNodes.getLength(); i++){
Node childNode = childrenBNodes.item(i);
ANode.appendChild(childNode);
}

//now remove the emptied <B>
ANode.removeChild(BNode);
 
M

Martin Honnen

Ha said:
I am trying to move a node of a tree up one level.
Example: I want to move C to be a child of A, then remove B.

Before:
<A>
<B>
<C>
<D/>
<E/>
</C>
</B>
</A>

After:
<A>
<C>
<D/>
<E/>
</C>
</A>

Here's the code I'm using. For some reason the children do not get added.
What am I missing?


NodeList nodeListB = document.getElementsByTagName("B");
Node BNode = nodeListMsgsRs.item(0);
Node ANode = eventsMsgsRsNode.getParentNode();

//these are the children of <B>
NodeList childrenBNodes = BNode.getChildNodes();

//add all of the children of <>B to B's parent <A>
for(int i =0; i<childrenBNodes.getLength(); i++){

Collections are live collections meaning the collection's length changes
while the loop executes.
You should use
while (BNode.hasChildNodes()) {
ANode.appendChild(BNode.getFirstChild());
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,999
Messages
2,570,244
Members
46,838
Latest member
KandiceChi

Latest Threads

Top