Skip to content

Instantly share code, notes, and snippets.

@viktor-evdokimov
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viktor-evdokimov/f7addc4aa95f39c5a470 to your computer and use it in GitHub Desktop.
Save viktor-evdokimov/f7addc4aa95f39c5a470 to your computer and use it in GitHub Desktop.
Convert html to xhtml with IE9
//IE9 +
var doc = new DOMParser().parseFromString('<img src="foo">', 'text/html');
var result = new XMLSerializer().serializeToString(doc);
// or
var di = document.implementation;
var hd = di.createHTMLDocument();
var xd = di.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
hd.body.innerHTML = '<img>';
var img = hd.body.firstElementChild;
var xb = xd.createElement('body');
xd.documentElement.appendChild(xb);
console.log('html doc:\n' + hd.documentElement.outerHTML + '\n');
console.log('xhtml doc:\n' + xd.documentElement.outerHTML + '\n');
img = xd.importNode(img); //or xd.adoptNode(img). Now img is a xhtml element
xb.appendChild(img);
console.log('xhtml doc after import/adopt img from html:\n' + xd.documentElement.outerHTML + '\n');
@viktor-evdokimov
Copy link
Author

first solution doesn't work in all versions of IE9.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment