The following JavaScript function is intended to open a new HTML page and to copy a div's content to it (the actual task is, of course, more complex than copying):
function copydiv(srcid) {
var w = window.open('about:blank', '_blank');
var otherdoc = w.document;
otherdoc.write('<html><body>');
otherdoc.write('</body></html>');
otherdoc.close();
var srcdiv = document.getElementById(srcid);
var otherbody = otherdoc.getElementsByTagName('body')[0];
// (A) var dstdiv = otherdoc.createElement('div');
// (A) otherbody.appendChild(dstdiv);
// (A) dstdiv.innerHTML = srcdiv.innerHTML;
// (B) otherbody.appendChild(srcdiv.cloneNode(true));
// (C) otherbody.appendChild(otherdoc.importNode(srcdiv, true));
}
The code parts marked (A) / (B) / (C) are alternatives; all three work in Firefox. However, only (A) works in Internet Explorer (11.49). The others throw the following exceptions:
- (B) HierarchyRequestError
- (C) Interface not supported
Although question JavaScript: cloneNode vs importNode suggests that “browsers don't enforce” the difference between cloneNode and importNode I would understand the need for the latter, as the source and destination nodes belong to different documents (which Firefox does not care about). But why doesn't Internet Explorer support importNode, given that it does not allow cloneNode in this case? Copying innerHTML seems an awkward way of cloning a node. Is there a better alternative to importNode for Internet Explorer? (Ideally it would be browser-independent.)