Skip to content

Instantly share code, notes, and snippets.

@hkfoster
Last active August 29, 2015 14:02
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 hkfoster/c63c201067aefc8e1425 to your computer and use it in GitHub Desktop.
Save hkfoster/c63c201067aefc8e1425 to your computer and use it in GitHub Desktop.
Native JS Node From String Function
/**
* 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 );
@krasimir
Copy link

krasimir commented Jul 3, 2014

That's a nice one!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment