Created
January 24, 2021 11:28
-
-
Save Dobby89/d78b50f0ccb3144583eee655a46b1175 to your computer and use it in GitHub Desktop.
htmlToElement / htmlToFragment - create HTML from a string
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
function htmlToElement(htmlString: string): HTMLElement { | |
const wrapper = document.createElement('div'); | |
wrapper.innerHTML = htmlString; | |
document.body.appendChild(wrapper); | |
const el = wrapper.firstChild; | |
if (el && wrapper.parentNode) { | |
const elClone = el.cloneNode(true); | |
wrapper.parentNode.removeChild(wrapper); | |
return elClone as HTMLElement; | |
} | |
return wrapper; | |
} |
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
function htmlToFragment(htmlString: string): DocumentFragment { | |
const fragment = document.createDocumentFragment(); | |
const wrapper = document.createElement('div'); | |
wrapper.innerHTML = htmlString; | |
Array.from(wrapper.childNodes).forEach((child) => | |
fragment.appendChild(child) | |
); | |
return fragment; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment