Last active
April 8, 2017 11:26
-
-
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
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 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