Acn
Acn

Reputation: 1066

Cloning node and appending to xml

I need some javascript (not JQuery etc) codes to copy a clone node and insert it just next to the copied node. For eg.

<a>
    <b>
        <ab></ab>
        <bc></bc>
    </b>
</a>

Now after copying the <b> node from the source xml and appending it as next sibling,

    <a>
        <b>
            <ab></ab>
            <bc></bc>
        </b>
        <!-- this is the copied node that will be appended. -->
        <b>
            <ab></ab>
            <bc></bc>
        </b>
        <!-- copied node ends here. -->
    </a>

I shall be grateful If some body show me some code example, which is supported in atleast Mozilla2 and IE5+. The CloneNode method doesnot works properly in many primitive version of major browsers. CloneNode is however supported in All IE browsers. So cloneNode method will not be a solution.

Upvotes: 1

Views: 932

Answers (1)

Abbas
Abbas

Reputation: 6886

Assuming that you are getting the required node by ID, here's how you can clone an existing node and append the clone as a sibling node:

var node = document.getElementById("toBeCloned");
var parentNode = node.parentNode;
alert(parentNode.outerHTML);
var clonedNode = node.cloneNode(true);
clonedNode.removeAttribute("id");
parentNode.appendChild(clonedNode);
alert(parentNode.outerHTML);

The alerts will show what the XML looked before and after the insertion.

This code will work with Mozilla and any reasonable version of IE. I cannot guarantee IE5 to IE7 support because I don't have access to those browsers.

Upvotes: 2

Related Questions