(moz|webkit)MatchesSelector vs. jQuery.is vs. Native Implementation (v2)

Revision 2 of this benchmark created by Cristian S. on


Description

Testing selector matching using (moz|webkit)MatchesSelector (implemented "matchesSelector" in Firefox and webkit browsers)

Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="level1">
    <div class="level2">
        <div class="level3">
            <div class="level4">
                <div class="level5" id="foo">
                </div>
                <div class="level5">
                </div>
                <div class="level5">
                </div>
            </div>
        </div>
    </div>
</div>
<script>
  (function(docEl, $) {
   var matches = docEl.mozMatchesSelector || docEl.webkitMatchesSelector;
   $.fn.matching = matches ?
   function(selector) {
    return matches.call(this[0], selector);
   } : $.fn.is;
  })(document.documentElement, jQuery);
  
  var matchesSelector = function(node, selector) {
   var nodeList = node.parentNode.querySelectorAll(selector),
       length = nodeList.length,
       i = 0;
   while (i < length) {
    if (nodeList[i] == node) return true;
    ++i;
   }
   return false;
  };
  
  var $element = jQuery(jQuery('.level1 .level2 .level3 .level4 .level5')[0]); // Get first result and add wrap with jQuery object
  var domEl = $element[0];
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Using $.fn.is
$element.is('.level1 .level2 .level3 .level4 .level5');
ready
Using mozMatchesSelector or webkitMatchesSelector
$element.matching('.level1 .level2 .level3 .level4 .level5');
ready
Native Implementation using querySelectorAll on Parent Node
matchesSelector(domEl, '.level1 .level2 .level3 .level4 .level5');
ready

Revisions

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