String to DOM Functions (v3)

Revision 3 of this benchmark created by Kyle Foster on


Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script>
/**
 * Node From String Function
 * @author Kyle Foster
 * @license MIT
 */
var nodeFromString = function( string ) {
  var match    = /^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/.exec( string ),
      tag      = match[ 1 ],
      content  = match[ 3 ],
      unwrap   = true,
      node     = document.createElement( tag ),
      outliers = [ 'legend', 'area', 'param', 'thead', 'tr', 'col', 'td' ];
  
  for ( var i = 0; i < outliers.length; i++ ) {
    if ( tag === outliers[ i ] ) { unwrap = false; }
  }
  
  if ( unwrap ) {
    node.innerHTML = string;
    return node.firstChild;
  } else {
    node.innerHTML = content;
    return node;
  }
};
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Node From String Function
// Create DOM element(s) from string
var text = nodeFromString( '<tr><td>Simple text</td></tr>' );

// Append to body
document.body.appendChild( text );
ready
jQuery Function
// Create DOM element(s) from string
var text = $( '<tr><td>Simple text</td></tr>' );

// Append to body
$( 'body' ).append( text );
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Kyle Foster on
  • Revision 2: published by Kyle Foster on
  • Revision 3: published by Kyle Foster on