Skip to content

Instantly share code, notes, and snippets.

@Dobby89
Created January 24, 2021 11:28
Show Gist options
  • Save Dobby89/d78b50f0ccb3144583eee655a46b1175 to your computer and use it in GitHub Desktop.
Save Dobby89/d78b50f0ccb3144583eee655a46b1175 to your computer and use it in GitHub Desktop.
htmlToElement / htmlToFragment - create HTML from a string
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;
}
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