DOM manipulation - moving a node

Discussion in 'XML' started by Ha, Jul 19, 2003.

  1. Ha

    Ha Guest

    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);
    Ha, Jul 19, 2003
    #1
    1. Advertising

  2. Ha wrote:
    > 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());
    }

    > Node childNode = childrenBNodes.item(i);
    > ANode.appendChild(childNode);
    > }
    >
    > //now remove the emptied <B>
    > ANode.removeChild(BNode);




    --

    Martin Honnen
    http://javascript.faqts.com/
    Martin Honnen, Jul 19, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    0
    Views:
    1,375
  2. Replies:
    0
    Views:
    359
  3. Tjerk Wolterink
    Replies:
    2
    Views:
    1,392
    Dimitre Novatchev
    Aug 24, 2006
  4. Armel Asselin
    Replies:
    6
    Views:
    1,057
    Armel Asselin
    Nov 16, 2006
  5. linkswanted
    Replies:
    0
    Views:
    606
    linkswanted
    Dec 21, 2007
Loading...

Share This Page