hasClass (v7)

Revision 7 of this benchmark created on


Preparation HTML

<span class="class1 class2">Test</span>
<span class="class1">Test</span>
<span class="class2">Test</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Setup

$.fn.extend({
      hasClassesForLoop: function (selectors) {
          var self = this;
          for (i in selectors) {
              if ($(self).hasClass(selectors[i])) 
                  return true;
          }
          return false;
      }
  });
  
  $.fn.extend({
       hasClassesRegex: function( selector ) {
  		var classNamesRegex = new RegExp("( " + selector.replace(/ +/g,"").replace(/,/g, " | ") + " )"),
  			rclass = /[\n\t\r]/g,
              i = 0,
  			l = this.length;
  		for ( ; i < l; i++ ) {
  			if ( this[i].nodeType === 1 && classNamesRegex.test((" " + this[i].className + " ").replace(rclass, " "))) {
  				return true;
  			}
  		}
  		return false;
  	},
  });

Test runner

Ready to run.

Testing in
TestOps/sec
hasclass
if ($('span').hasClass('class1') || $('span').hasClass('class2')){
console.log('hasClass')
}
ready
is
if ($('span').is('class1, .class2')){
console.log('is')
}
ready
.hasClasses() with for loop
if ($('span').hasClassesForLoop(['class1', 'class2'])){
console.log('is')
}
ready
.hasClasses() with Regex
if ($('span').hasClassesRegex('class1, class2')){
console.log('is')
}
ready

Revisions

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