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


i trying figure out how check if parent div has child p element without 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 div not have p element class "a", want hide div.

how this?

i tried:

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

but not seem work

thanks

you can use jquery :has() , :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, can take 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>


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -