hasClass vs length (different scenarios)

Benchmark created on


Preparation HTML

<div>
<div>
<div>
<div class="a">

<ul class="drop-menu">
 <li class="expanded"><a href="#"><span>Expanded One</span></a>
  <ul class="drop-sub-menu">
   <li class="list-item-one"><label for="chkLabelOne"><input type="checkbox" id="chkBoxOne" class="inputValueOne" />Check Box One</label></li>
   <li class="list-item-two"><label for="chkLabelTwo"><input type="checkbox" id="chkBoxTwo" class="inputValueTwo" />Check Box Two</label></li>
  </ul>
 </li>
</ul>

<ul class="drop-menu">
 <li class="expanded"><a href="#"><span>Expanded Two</span></a>
  <ul class="drop-sub-menu-two">
   <li class="list-item-one"><label for="chkLabelOne"><input type="checkbox" id="Checkbox1" class="inputValueOne" />Check Box One</label></li>
   <li class="list-item-two"><label for="chkLabelTwo"><input type="checkbox" id="Checkbox2" class="inputValueTwo" />Check Box Two</label></li>
  </ul>
 </li>
</ul>

<ul class="drop-menu">
 <li class="expanded"><a href="#"><span>Expanded Three</span></a>
  <ul class="drop-sub-menu-three">
   <li class="list-item-three"><label for="chkLabelThree"><input type="checkbox" id="Checkbox4" class="inputValueThree" />Check Box Three</label></li>
   <li class="list-item-three"><label for="chkLabelThree"><input type="checkbox" id="Checkbox7" class="inputValueThree" />Check Box Three</label></li>
   <li class="list-item-three"><label for="chkLabelThree"><input type="checkbox" id="Checkbox8" class="inputValueThree" />Check Box Three</label></li>
   <li class="list-item-three"><label for="chkLabelThree"><input type="checkbox" id="Checkbox9" class="inputValueThree" />Check Box Three</label></li>
  </ul>
 </li>
</ul>

<ul class="drop-menu">
 <li class="expanded"><a href="#"><span>Expanded Four</span></a>
  <ul class="drop-sub-menu-four">
   <li class="list-item-four"><label for="chkLabelFour"><input type="checkbox" id="Checkbox6" class="inputValueFour" />Check Box Four</label></li>
  </ul>
 </li>
</ul>

</div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  var tf;
  var $parent = $('ul');
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
hasClass method
if ($parent.hasClass('drop-menu')) {
 tf = $parent.find('.inputValueOne').addClass('Mick');
}
ready
length
if ($("input.inputValueTwo").length > 0) {
 tf = $parent.find('.inputValueTwo').addClass('Ronnie');
}
ready
hasClass - check multiple tags based on 'has' method
if ($parent.hasClass('drop-sub-menu-three')) {
 tf = $parent.find('.inputValueThree').addClass('Keith');
}
ready
hasClass - tag + class name variable
var $namedParent = $('ul.drop-menu');
if ($parent.hasClass('drop-sub-menu-four')) {
 tf = $parent.find('.inputValueFour').addClass('Charlie');
}
ready

Revisions

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