DearBee
DearBee

Reputation: 426

jQuery If children of element have two classes - do something

I want to catch if children of element have two classes, so for example if we have something like this:

HTML

<div class="mainElement">
  <div>
    <p class="thisClass">
    </p>
  </div>
  <div>
    <div>
      <div class="andThisClass">
    </div>
  </div>
</div>

I would like to catch it and remove it, for example like this:

jQuery

if($('.mainElement').hasClasses('thisClass, andThisClass') ){
$('.mainElement').css('display', 'none');

}

Though this obviously wouldn't work, I've also tried with .find().

Upvotes: 1

Views: 49

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

You could do it with has filter,

var cache = $('.mainElement');
cache.toggle(!(cache.has('.thisClass').length && cache.has('.andThisClass').length));

DEMO

Upvotes: 2

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

You can do it using .find

Try like this

if ($('.mainElement').find('.thisClass').length>0 && $('.mainElement').find('.andThisClass').length>0) {
  console.log("contain");
}

DEMO

you didn't close your tag properly

here

    </p>
  </div  <- here
  <div>
    <div>

Upvotes: 1

Related Questions