Skip to content

Instantly share code, notes, and snippets.

@nuxodin
Last active April 8, 2017 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuxodin/09925eabf077c6989617a2fb1aa303a1 to your computer and use it in GitHub Desktop.
Save nuxodin/09925eabf077c6989617a2fb1aa303a1 to your computer and use it in GitHub Desktop.
string to dom-nodes with support for old ie's and table-elements
function stringToFragment(html){
var tmpl = document.createElement('template');
tmpl.innerHTML = html;
if (tmpl.content == void 0){ // ie11
var fragment = document.createDocumentFragment();
var isTableEl = /^[^\S]*?<(t(?:head|body|foot|r|d|h))/i.test(html);
tmpl.innerHTML = isTableEl ? '<table>'+html : html;
var els = isTableEl ? tmpl.querySelector(RegExp.$1).parentNode.childNodes : tmpl.childNodes;
while(els[0]) fragment.appendChild(els[0]);
return fragment;
}
return tmpl.content;
}
// parses a string to a document.fragment
// supports old ie's (tested in ie11)
// and there, it supports table-elements like td, tr...
//
// if you like only the first element, use it like this:
// stringToFragment('<img src="....">').firstChild;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment