ClassName Matches

Benchmark created by Arexkun on


Preparation HTML

<div class="tra"></div>
<div class="foo"></div>
<div class="bar"></div>
<div class="foo bar"></div>
<div class="tra foo"></div>
<script>
  var l = document.getElementsByTagName("div");
  re_c = {};
  
  alert(l.length)
  
  function re(str) {
   return re_c[str] = re_c[str] || new RegExp(str);
  }
  
  function matchesClass1(list, classes) {
   var x, y, ret = [],
       cls;
   for (x = 0; x < list.length; x++) {
    cls = " " + list[x].className + " ";
    for (y in classes) {
     if (cls.indexOf(" " + classes[y] + " ") >= 0) {
      ret.push(list[x]);
      break;
     }
    }
   }
   return ret;
  }
  
  function matchesClass2(list, classes) {
   var reg = re(" (" + classes.join("|") + ") "),
       x, ret = [];
   for (x = 0; x < list.length; x++) {
    reg.test(" " + list[x].className + " ") && ret.push(list[x]);
   }
   return ret;
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
indexOf
matchesClass1(l, ["foo"])
ready
RegEx
matchesClass2(l, ["foo"])
ready

Revisions

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