Beginner
Beginner

Reputation: 29543

jQuery: check if a div contains a div with class on

I have several <div> elements inside another <div>.

I want to do an if statement which is true if a div inside the top div contains class on.

HTML:

<div class="toDiv">
    <div>

    </div>
    <div class="on">

    </div>
</div>

jQuery:

if ($(".toDiv").contains("on")) {
    // do something
}

Upvotes: 41

Views: 72979

Answers (2)

Ropstah
Ropstah

Reputation: 17804

$('div.toDiv').each(function() {
    if($('div.on', this).length > 0) {
        //do something with this
    }
});

Upvotes: 9

Claudio Redi
Claudio Redi

Reputation: 68400

if ($(".toDiv").find(".on").length > 0){ 
  ///do something
}

or

if ($(".toDiv .on").length > 0){ 
  ///do something
}

Upvotes: 93

Related Questions