Last active
August 29, 2015 14:02
-
-
Save hkfoster/c63c201067aefc8e1425 to your computer and use it in GitHub Desktop.
Native JS Node From String Function
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
/** | |
* Node From String Function | |
* @author Kyle Foster | |
* @license MIT (http://www.opensource.org/licenses/mit-license.php/) | |
*/ | |
var nodeFromString = function( string ) { | |
var match = /^<([a-z]+)/g.exec( string ), | |
tag = match[ 1 ], | |
wrapper = 'div', | |
outliers = { | |
option : 'select', | |
legend : 'fieldset', | |
area : 'map', | |
param : 'object', | |
thead : 'table', | |
tr : 'tbody', | |
col : 'colgroup', | |
td : 'tr' | |
}; | |
for ( var key in outliers ) { | |
if ( tag === key ) { wrapper = outliers[ key ]; } | |
} | |
var node = document.createElement( wrapper ); | |
node.innerHTML = string; | |
return node.firstChild; | |
}; | |
// Create node from string | |
var text = nodeFromString( '<tr><td>Simple Text</td></tr>' ); | |
// Append to body | |
document.body.appendChild( text ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's a nice one!