IE support for DOM importNode

There is a function document.importNode() in Internet Explorer 9 DOM API. However, IE9 throws a script error when it’s called

SCRIPT16386: No such interface supported

Also there is need to define namespace of source node (e.g., when we want to import SVG – In IE9, Imported nodes do not seem to be recognized as SVG Elements)

Phrogz suggested this useful workaround. However, when we import element which has special namespace (declared in xmlns attribute, e.g. <svg xmlns="http://www.w3.org/2000/svg" …>…</svg>) there will be error in clone.setAttributeNS(a.namespaceURI,a.nodeName,a.nodeValue) because namespaceURI for attribute xmlns is null.

There is workaround which work for me:

var newNode;
try {
  newNode = document.importNode(sourceDocumentElement, true);
}
catch(e) {
  newNode = importNode(sourceDocumentElement, true);
}

function importNode(node, allChildren) {
  switch (node.nodeType) {
    case document.ELEMENT_NODE:
      var newNode = document.createElementNS(node.namespaceURI, node.nodeName);
      if(node.attributes && node.attributes.length > 0)
        for(var i = 0, il = node.attributes.length; i < il; i++)
          newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i].nodeName));
      if(allChildren && node.childNodes && node.childNodes.length > 0)
        for(var i = 0, il = node.childNodes.length; i < il; i++)
          newNode.appendChild(importNode(node.childNodes[i], allChildren));
      return newNode;
      break;
    case document.TEXT_NODE:
    case document.CDATA_SECTION_NODE:
    case document.COMMENT_NODE:
      return document.createTextNode(node.nodeValue);
      break;
  }
}

Leave a Comment