Find following element with class

JavaScript performance comparison

Test case created by Bob Myers

Info

Depends on webkitMatchesSelector.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.0.6-development-only.js"></script>

<div>
  <div class="x"></div>
  <div id="start" class="x"></div>
<div>
<div
 <div class="x">
</div>
<script>
Benchmark.prototype.setup = function() {
    var query_selector=(function(){
   
        //return the previous or next node of interest
        function adjacent(n,d){
            var nn,sib=d?'nextSibling':'previousSibling';
            while(n){
                nn=n[sib];
                if(nn){return nn;}
            }
            return null;
        }
   
        //does the current node satisfy the selector?
        function self(n,s){
            var ms=n&&n.webkitMatchesSelector;
            return ms&&ms.call(n,s);
        }
   
        //do descendant nodes satisfy the selector?
        function descendants(n,s){
            var qs=n&&n.querySelector;
            return qs&&qs.call(n,s);
        }
   
        //does either the current node OR descendant nodes satisfy the selector?
        function self_or_descendants(n,s){return n&&(self(n,s)||descendants(n,s));}
   
        //find the most recent matching node in the specified direction
        function move(n,s,d,r){
            while(!r&&n){
                n=adjacent(n,d);
                r=self_or_descendants(n,s);
            }
            return r;
        }
   
        return {
            following:function(n,s){return move(n,s,true,  descendants(n           , s));},
            preceding:function(n,s){return move(n,s,false, n&&self    (n.parentNode, s));}
        };
    }());
   
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
jQuery
var $x = $('.x');
var $next = $x.eq($x.index(document.getElementById("start")) + 1);
pending…
DOM
var $next=query_selector.following(document.getElementById("start",".x"));
pending…

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

Compare results of other browsers

0 comments

Add a comment