Quantcast
Channel: Software Salad
Viewing all articles
Browse latest Browse all 21

IE’s cloneNode doesn’t actually clone!

$
0
0

When you want to deeply clone a node you use the cloneNode(true) method on the element you want to clone (see w3′s DOM Level 2 specifications)

IE Cant even clone

IE Cant even clone


I found that IE’s cloneNode method is broken. Yes, broken! If you want the cloned DOM structure to be exactly the same (i.e. a clone) then don’t use cloneNode. Take this example:

    var container = document.createElement("div");
    container.appendChild(document.createTextNode("Apples"));
    container.appendChild(document.createTextNode("Oranges"));
    alert(container.firstChild.nodeValue); // Will Print "Apples"

    container = container.cloneNode(true);
    alert(container.firstChild.nodeValue); // Prints "ApplesOranges" on IE!

As pointed out by the comments in the example above, the cloneNode operation consolidates the two text nodes together as one! This is incorrect!

If you need cloneNode to keep the structure cloned, then you could write your own deep-clone method. Here is an implementation:

    /**
     * Deeply clones a node
     * @param {Node} node A node to clone
     * @return {Node} A clone of the given node and all its children
     */
    function cloneNode(node) {
    	// If the node is a text node, then re-create it rather than clone it
        var clone = node.nodeType == 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
   
        // Recurse     
        var child = node.firstChild;
        while(child) {
            clone.appendChild(cloneNode(child));
            child = child.nextSibling;
        }
        
        return clone;
    }

Happy coding!


Posted in Programming Problems - Resolved, Web Programming Tagged: browser, clonenode, cloning, code, dom, dom level 2, element, html, ie, internet explorer, javascript, js, node, Programming, textnode, w3c, web

Viewing all articles
Browse latest Browse all 21

Trending Articles