DOM manipulation - moving a node

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ha

    #1

    DOM manipulation - moving a node

    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.getEle mentsByTagName( "B");
    Node BNode = nodeListMsgsRs. item(0);
    Node ANode = eventsMsgsRsNod e.getParentNode ();

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

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

    //now remove the emptied <B>
    ANode.removeChi ld(BNode);
  • Martin Honnen

    #2
    Re: DOM manipulation - moving a node

    Ha wrote:[color=blue]
    > 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.getEle mentsByTagName( "B");
    > Node BNode = nodeListMsgsRs. item(0);
    > Node ANode = eventsMsgsRsNod e.getParentNode ();
    >
    > //these are the children of <B>
    > NodeList childrenBNodes = BNode.getChildN odes();
    >
    > //add all of the children of <>B to B's parent <A>
    > for(int i =0; i<childrenBNode s.getLength(); i++){[/color]

    Collections are live collections meaning the collection's length changes
    while the loop executes.
    You should use
    while (BNode.hasChild Nodes()) {
    ANode.appendChi ld(BNode.getFir stChild());
    }
    [color=blue]
    > Node childNode = childrenBNodes. item(i);
    > ANode.appendChi ld(childNode);
    > }
    >
    > //now remove the emptied <B>
    > ANode.removeChi ld(BNode);[/color]



    --

    Martin Honnen


    Comment

    Working...