Skip to content

Instantly share code, notes, and snippets.

@krrishd
Last active August 29, 2015 14:07
Show Gist options
  • Save krrishd/494a15b007d0e9d2920b to your computer and use it in GitHub Desktop.
Save krrishd/494a15b007d0e9d2920b to your computer and use it in GitHub Desktop.
Simple JS to convert a string of valid HTML to an HTMLDocument object (that you can interact with as you would with the DOM)
/* Usage:
* var html = '<!DOCTYPE html><html><head></head><body></body></html>';
* var htmlDocument = html.toHTML();
* HTMLDocument.prototype.isPrototypeOf(htmlDocument) => returns true
*/
String.prototype.toHTML = (function() {
function toHTML(str) {
var dom = new DOMParser();
var doc = dom.parseFromString(str, 'text/html');
return doc;
}
return function() { return toHTML(this); }
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment