Selecting an element by ID

Benchmark created by David Mark on


Description

The most basic browser scripting operation: retrieving an element reference by ID.

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
/*
 * Context here is an HTML5 document
 * Appropriate build for this context would exclude XHTML support
 * Next line asserts document will create an HTML DOM
 * There are virtually no documents on the Web that create an XHTML DOM
 *
 */
var API = { disableXmlParseMode:true };
</script>
<script src="//www.cinsoft.net/mylib099-min.js"></script>
<script>
  // For My Library test
  
  var getEBI = API.getEBI;
  
  // For cross-browser test
  
  // NOTE: Should use isHostMethod (or variation) for host feature detection
  // Degrades in IE 4 :)
  
  if (document.getElementById) {
    var getElement = function(id) {
  
      var el = document.getElementById(id);
  
      // Can remove next bit if name/ID issues not present in markup
      // Fails immediately on name/ID mixup (as seen in legacy IE browsers)
      // If not sure, leave it in.
  
      if (el.id != id) {
        return null;
      }
      return el;
    };
  }
  
  // For all tests
  
  var el;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
My Library
// Can name "getEBI" function anything (even "$")

// Concise, readable, minifies well (if not global code) :)

el = getEBI('author');
ready
jQuery
// jQuery doesn't have a select-one :(

// Relatively long-winded and obscure, minifier can't touch it. :(

el = jQuery('#author')[0];
ready
Cross-browser
// NOTE: API feature detection not normally in loop

if (getElement) {
  el = getElement('author');
} else {
  throw new Error('Abort due to degraded browser');
}
 
ready

Revisions

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

  • Revision 1: published by David Mark on