Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.