Anagio
Anagio

Reputation: 3075

jQuery check if any div on page has specific class in an if statement

I'm using Bootstrap switch https://github.com/nostalgiaz/bootstrap-switch and have a few switches in a table.

When a switch is toggled I check the state of the switch and have a basic if condition. When the data.value is false the switch has been turned off. I tried to run another conditional to check if any of the switches in the table, had the switch-on class, and if so hide a series in high charts. This isn't working as expected. I'm pretty sure my selector is ok div.make-switch > div is selecting the first nested div, which has the class switch-on or switch-off

Whats wrong with the code? Shouldn't my second if condition fire every time the switches are turned off and check if any of the switches are on?

Thanks

The HTML rendered by the on and off states is below,

if(data.value == true){
// Switch is on
}
else if (data.value == false){
// Switch is off

    if ($('div.make-switch > div').hasClass('switch-on')){

        series.hide();
    }
}

Off state has class .switch-off in nested div

<div class="make-switch switch-mini has-switch"><div class="switch-off switch-animate"><input name="" id="create-switch" type="checkbox"><span class="switch-left switch-mini">ON</span><label class="switch-mini" for="create-switch">&nbsp;</label><span class="switch-right switch-mini">OFF</span></div></div>

On state has class .switch-on in nested div

<div class="make-switch switch-mini has-switch"><div class="switch-on switch-animate"><input name="" id="create-switch" type="checkbox"><span class="switch-left switch-mini">ON</span><label class="switch-mini" for="create-switch">&nbsp;</label><span class="switch-right switch-mini">OFF</span></div></div>

Upvotes: 1

Views: 2758

Answers (1)

Jason P
Jason P

Reputation: 27022

Try this:

if ($('div.make-switch > div.switch-on').length) {

If an element exists that matches the selector, the length property will return a "truthy" result.

Upvotes: 4

Related Questions