Peter Kanba
Peter Kanba

Reputation: 21

Match Divs by class and check if they contain a class using Js

How can I check a div by class (top) if he has an other div with an other class(bottom) inside so that the function returns a true or false in an array.

<div class="top">
  <div class="bottom"></div>
</div>
<div class="top"></div>

I tried this but It only told me if the <div class="top"> contains the <div class="bottom"> and not if the <div class="top"> comes without the <div class="bottom">

if ($(".top").find(".bottom").length > 0){ 

}

Upvotes: 2

Views: 31

Answers (1)

Steven
Steven

Reputation: 381

You can exclude the ".top"-div's without ".bottom" with the has-method:

$('.top').has('.bottom').css('background', '#bada55');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top">
  top has bottom
  <div class="bottom">bottom</div>
</div>
<div class="top">top without bottom</div>

Upvotes: 1

Related Questions