CSS4 :nth-match Selector in jQuery

Benchmark created by Tom Ellis on


Description

Testing the CSS4 :nth-match Selector in jQuery to see if jQuery.expr.filters.CHILD is quicker than using .is()

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<a class="link" href="http://localhost/css4/">Home</a>
<a class="link" href="http://localhost/css4/blog/">Blog</a>
<a class="link" href="http://www.localhost/css4/about/">About</a>
<a href="http://localhost/css4/search/1/" class="test">Search</a>
<a class="link" href="http://localhost/css4/contact/" class="test2">Contact</a>
<a href="http://www.google.co.uk" class="test2">Google!</a>

Setup

var re_match = /:(nth)-match(?:[0-9])?(?:\((even|odd|[\dn+-]*),(.*?)\))?/,
      // Method / object references.
      $expr = $.expr, filterCHILD = $expr.filter.CHILD;
    
      $.extend($.expr[":"], {
        "nth-match1": function(elem, i, m) {
          var arr = m[3].split(","),
              n = arr[0],
              selector = arr[1],
              $this = $(elem),
              matches = m[0].match(re_match);
    
          matches = $expr.preFilter.CHILD(matches);
    
          return elem.parentNode && $this.is(selector) && filterCHILD(elem, matches);
        },
        "nth-match2": function(elem, i, m) {
          var arr = m[3].split(","),
              n = arr[0],
              selector = arr[1],
              $this = $(elem);
    
          return elem.parentNode && $this.is(selector) && $this.is(":nth-child(" + n + ")");
        }
      });

Test runner

Ready to run.

Testing in
TestOps/sec
Using Sizzle's filter.CHILD
$("a:nth-match1(odd, a.link)").css("color", "red");
ready
Using jQuery's :is()
$("a:nth-match2(odd, a.link)").css("color", "red");
 
ready

Revisions

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

  • Revision 1: published by Tom Ellis on