Created
April 18, 2020 03:16
-
-
Save kuoruan/b9c7ba6e315d92f4f6c773e5cd1cceb6 to your computer and use it in GitHub Desktop.
Convert HTML string to document fragment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const rangeFragmentSuport = | |
"createContextualFragment" in document.createRange(); | |
export const templateSupport = "content" in document.createElement("template"); | |
export function htmlFragment(html: string): DocumentFragment { | |
if (rangeFragmentSuport) { | |
return document.createRange().createContextualFragment(html); | |
} | |
if (templateSupport) { | |
const template = document.createElement("template"); | |
template.innerHTML = html; | |
return template.content; | |
} | |
const doc = document.implementation.createHTMLDocument(""), | |
range = doc.createRange(), | |
body = doc.body; | |
body.innerHTML = html; | |
range.selectNodeContents(body); | |
return range.extractContents(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment