Created
July 1, 2014 07:47
-
-
Save DChinin/0960de5a65bec4e4f011 to your computer and use it in GitHub Desktop.
Create DOM element by string http://www.sitepoint.com/revealing-magic-javascript/
This file contains 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
var stringToDom = function(str) { | |
var wrapMap = { | |
option: [1, '<select multiple="multiple">', '</select>'], | |
legend: [1, '<fieldset>', '</fieldset>'], | |
area: [1, '<map>', '</map>'], | |
param: [1, '<object>', '</object>'], | |
thead: [1, '<table>', '</table>'], | |
tr: [2, '<table><tbody>', '</tbody></table>'], | |
col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], | |
td: [3, '<table><tbody><tr>', '</tr></tbody></table>'], | |
_default: [1, '<div>', '</div>'] | |
}; | |
wrapMap.optgroup = wrapMap.option; | |
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; | |
wrapMap.th = wrapMap.td; | |
var element = document.createElement('div'); | |
var match = /<\s*\w.*?>/g.exec(str); | |
if(match != null) { | |
var tag = match[0].replace(/</g, '').replace(/>/g, ''); | |
var map = wrapMap[tag] || wrapMap._default, element; | |
str = map[1] + str + map[2]; | |
element.innerHTML = str; | |
// Descend through wrappers to the right content | |
var j = map[0]+1; | |
while(j--) { | |
element = element.lastChild; | |
} | |
} else { | |
// if only text is passed | |
element.innerHTML = str; | |
element = element.lastChild; | |
} | |
return element; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment