jquery get first child (v2)

Revision 2 of this benchmark created by Dan Manastireanu on


Description

Test the performance of different methods to get the first child in jquery

Preparation HTML

<div id="test">
<span>first</span>
<span>second</span>
<span>....</span>
<span>....</span>
<span>....</span>
<span>....</span>
<span>....</span>
<span>....</span>
<span>....</span>
<span>....</span>
<span>....</span>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  function assertEq(expected, actual) {
   if (expected !== actual) {
    throw new Error('Expected "' + expected + '" but found "' + actual + '"');
   }
  }
  
  function isValid(el) {
   assertEq('first', el.text());
  }
  
  (function($) {
   $.fn.down = function() {
    return $(this[0] && this[0].children && this[0].children[0]);
   };
   //implementation from prototype library
   $.fn.downP = function() {
    var el = this[0] && this[0].firstChild;
    while (el && el.nodeType != 1) el = el.nextSibling;
    return $(el);
   }
  })(jQuery);
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
children().first();
isValid($('#test').children().first());
ready
children(':eq(0)');
isValid($('#test').children(':eq(0)'));
ready
down
isValid($('#test').down());
ready
children(':first');
isValid($('#test').children(':first'));
ready
*:first
isValid($('#test *:first'));
ready
children().eq(0);
//first() is just a shortcut for eq(0)
isValid($('#test').children().eq(0));
ready
find(':first');
isValid($('#test').find(':first'));
ready
downP
//adapted from prototype library
isValid($('#test').downP());
ready

Revisions

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

  • Revision 1: published by Dan Manastireanu on
  • Revision 2: published by Dan Manastireanu on
  • Revision 3: published on