Various ways of getting element by id

JavaScript performance comparison

Test case created by T.J. Crowder

Preparation code

<!-- Normally you don't want to do this, it returns something that can only be cached for a day. Normally you want to ask for a specific version, which can be cached for a year. But for a test like this it makes sense. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div>
    <div id="element"></div>
</div>

      
<script>
Benchmark.prototype.setup = function() {
  function gid(id){
      return document.getElementById(id);
  }
  function $gid(id){
      var elm = document.getElementById(id);
      return elm ? $(elm) : $();
  }
  

};
</script>

Preparation code output

<!-- Normally you don't want to do this, it returns something that can only be cached for a day. Normally you want to ask for a specific version, which can be cached for a year. But for a test like this it makes sense. --> <div> <div id="element"></div> </div>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
jQuery $
if (!$('#element')[0]) throw "Error in test";
pending…
getElementById direct
if (document.getElementById('element') == null) throw "Error in test";
pending…
getElementById wrapped
if (gid('element') == null) throw "Error in test";
pending…
querySelector
if (document.querySelector('#element') == null) throw "Error in test";
pending…
querySelectorAll
if (document.querySelectorAll('#element')[0] == null) throw "Error in test";
pending…

Compare results of other browsers

Revisions

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

0 Comments