badcoder
badcoder

Reputation: 3834

How to check if child element does not have a class using jQuery

I am trying to figure out how to check if a parent div has a child p element without a certain class.

So e.g.

    <div id="one" class="item">
        <p class="A"></p>
        <p class="B"></p>
        <p class="C"></p>
    </div>

    <div id="two" class="item">
        <p class="B"></p>
        <p class="C"></p>
    </div>

If the div does not have a p element with the class "A", I want to hide that div.

How would I do this?

I tried:

if (jQuery(".item > p.A").length <= 0){
    //run code here
}

but that does not seem to work

Thanks

Upvotes: 0

Views: 4279

Answers (2)

AmmarCSE
AmmarCSE

Reputation: 30557

You can use jQuery :has() and :not() like

$('div:not(:has(p.A))').hide();

$('div:not(:has(p.A))').hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="one" class="item">
        <p class="A">A</p>
        <p class="B">B</p>
        <p class="C">C</p>
    </div>

    <div id="two" class="item">
        <p class="B">B</p>
        <p class="C">C</p>
    </div>

Or, you can take an iterative approach

$('div').each(function() {
  if ($(this).has('p.A').length == 0) {
    $(this).hide();
  }
});

$('div').each(function() {

  if ($(this).has('p.A').length == 0) {
    $(this).hide();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="one" class="item">
  <p class="A">A</p>
  <p class="B">B</p>
  <p class="C">C</p>
</div>

<div id="two" class="item">
  <p class="B">B</p>
  <p class="C">C</p>
</div>

Upvotes: 4

Michelangelo
Michelangelo

Reputation: 5948

You can also do something like this. In my opinion this describes better what you are doing and is easier when you read it back. Fiddle: http://jsfiddle.net/ayxdm7y3/

if ($('div').children().hasClass("A")){
   console.log("yes");
}

Upvotes: 0

Related Questions