Skip to content

Instantly share code, notes, and snippets.

@nanto
Forked from snaka/HTMLStringToDOM.js
Created August 8, 2009 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nanto/164328 to your computer and use it in GitHub Desktop.
Save nanto/164328 to your computer and use it in GitHub Desktop.
/*
* HTMLParser for Greasemonkey by snaka(http://d.hatena.ne.jp/snaka72/)
*
* Original coode written by swdyh(http://d.hatena.ne.jp/swdyh/)
* This code includes part of AutoPagerize(http://userscripts.org/scripts/show/8551)
*
* Released under the GPL license
* http://www.gnu.org/copyleft/gpl.html
*/
var HTMLStringToDOM = (function() {
function createHTMLDocumentByString(str) {
if (document.documentElement.nodeName != 'HTML') {
return new DOMParser().parseFromString(str, 'application/xhtml+xml')
}
var html = strip_html_tag(str)
var htmlDoc
try {
// We have to handle exceptions since Opera 9.6 throws
// a NOT_SUPPORTED_ERR exception for |document.cloneNode(false)|
// against the DOM 3 Core spec.
htmlDoc = document.cloneNode(false)
htmlDoc.appendChild(htmlDoc.importNode(document.documentElement, false))
}
catch(e) {
htmlDoc = document.implementation.createDocument(null, 'html', null)
}
var fragment = createDocumentFragmentByString(html)
try {
fragment = htmlDoc.adoptNode(fragment)
}
catch(e) {
fragment = htmlDoc.importNode(fragment, true)
}
htmlDoc.documentElement.appendChild(fragment)
return htmlDoc
}
function createDocumentFragmentByString(str) {
var range = document.createRange()
range.setStartAfter(document.body)
return range.createContextualFragment(str)
}
function strip_html_tag(str) {
var chunks = str.split(/(<html(?:[ \t\r\n][^>]*)?>)/)
if (chunks.length >= 3) {
chunks.splice(0, 2)
}
str = chunks.join('')
chunks = str.split(/(<\/html[ \t\r\n]*>)/)
if (chunks.length >= 3) {
chunks.splice(chunks.length - 2)
}
return chunks.join('')
}
return createHTMLDocumentByString;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment