jQuery multiple first child selection (v6)

Revision 6 of this benchmark created on


Description

Finding the best way to select the first children of each element of a jQuery collection. Based on http://jsperf.com/jquery-first-child-selection-performance/6, but this test selects the first child of multiple elements, always returns a jQuery collection, and includes other markup on the page for more realistic performance.

Queries using .first() or ':first' return only a single element, but have been included for comparison, and because they will work correctly when selecting on a single element.

Preparation HTML

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

var testnodes = '';
for (var i=0; i<20; i++){
  testnodes += "<div class='test'></div>";
}

 var content = '';
 for (var i = 0; i < 500; i++) {
  content += '<div class="lkjsf' + i + '"></div>';
 }

 var otherJunk = '';
 for (var i = 0; i < 5000; i++) {
  otherJunk += '<div id="junk' + i + '"><div class="junkchild"></div></div>';
 }

$('body')
  .append(testnodes)
  .append(otherJunk);

$('.test').append(content);


$.fn.firstChild = function() {
                var ret = [];
                
                this.each(function(){
                        var el = this.firstChild;
                        
                        //the DOM firstChild property could return a text node or comment instead of an element
                        while (el && el.nodeType != 1)
                                el = el.nextSibling;
                        
                        if (el) ret.push(el);
                });
                
                //maintain jQuery chaining and end() functionality
                return this.pushStack(ret);
            };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
first
$('.test :first')
ready
direct first
$('.test > :first')
ready
direct first-child
$('.test > :first-child')
ready
direct nth-child
$('.test > :nth-child(1)')
ready
find first
$('.test').find(':first')
ready
find direct first
$('.test').find('> :first')
ready
find direct first-child
$('.test').find('> :first-child')
ready
children first
$('.test').children(":first")
ready
children first-child
$('.test').children(":first-child")
ready
jQuery firstChild
//custom function; see setup code
$('.test').firstChild()
ready
jQuery eq(0)
$('.test > :eq(0)')
ready
Native querySelectorAll
$( document.body.querySelectorAll('div.test > :first-child') )
ready
children() first()
$('.test').children().first()
ready
children[0]
$('.test').children()[0]
ready
children eq(0)
$('.test').children().eq(0)
ready
direct first()
$('.test > *').first()
ready

Revisions

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