How to check if an element has multiple CSS classes in jQuery

I have html as below. I go through all the elements inside a div (accordionContents). Inside the loop, I need to check the condition if the h2 element applies two css classes (acc_trigger and active) or not. How can i do this?

<div id="accordionContents"> <div class="accordioncontainer"> <h2 class="acc_trigger active"> <a href="#"> <img class="openImage" src="Images/closed.png"> <div class="openHeader">Division : <b>Quality Assurance</b>(4 items)</div></a></h2> <div class="acc_container" style="display: block;"> <div class="dataRowTeam"> <div class="riskStartContent"> <div class="riskGridHeader"> weekStart</div> </div> <div class="riskEndContent"> <div class="riskGridHeader"> 90%</div> </div> </div> </div> </div> <div class="accordioncontainer"> <h2 class="acc_trigger"> <a href="#"> <img class="openImage" src="Images/closed.png"> <div class="openHeader">Division : <b>Quality Assurance</b>(4 items)</div></a></h2> <div class="acc_container" style="display: none;"> <div class="dataRowTeam"> <div class="riskStartContent"> <div class="riskGridHeader"> weekStart</div> </div> <div class="riskEndContent"> <div class="riskGridHeader"> 90%</div> </div> </div> </div> </div> </div> 
+4
source share
5 answers

In your particular case, this should be enough:

 var hasActive = $('.acc_trigger').hasClass("active"); // Bool. TRUE / FALSE if(hasActive){ // do something if TRUE } 

Otherwise, you can go directly to the existence of the element

 $('.acc_trigger.active').css({background: 'red'}); 

Live demo

By the way, your HTML formatting is pretty unusual, I would rather say wrong:
DIV (block level elements) must not be inside A (built-in) elements

+4
source

try asking hasClass more than once;)

 $(".accordionContents").each(function(){ var $headline = $("h2", this).first(); var hasBothCSSClasses = $headline.hasClass('acc_trigger') & $headline.hasClass('active'); }); 
0
source

Try the following: http://jsfiddle.net/jH8RF/1/

 var clslen = $('h2').attr('class').split(' ').join(','); var len = clslen.indexOf(','); if( len > 0){ alert('elem has more than one class'); }else{ alert('elem has just one class'); } 
0
source

Try the following:

 $('.accordionContents h2').each(function() { if ($(this).is('.acc_trigger.active')) { // do something... }) }); 
0
source
 var strValue = $("h2").prop('class').trim(); if(strValue.indexOf(" ") > -1) { //This element has multiple classes. } else { //This element has a single class. } 
0
source

All Articles