Get all parents who don’t have a child with a particular class.

I want to select all div parents using jQuery that don't have children with class locked

Code example:

<div class='myparent'>
    <div class='mychild locked'></div>
</div>
<div class='myparent'>
    <div class='mychild locked'></div>
</div>
<div class='myparent'>
    <div class='mychild'></div>
</div>

I feel very close:

$('div.myparent:not(:has(div[class=locked]))')

But that does not work.

+4
source share
3 answers

You can just use the class selector, no DEMO attribute selector needed

$('.myparent:not(:has(div.locked))')

Note: you can do this too: - $('.myparent:not(:has(.locked))')

+7
source
  • and use not () to exclude the locked class, then use the parent to lock the parent

$(".mychild:not(.locked)").parent().css("color","red")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='myparent'>
    <div class='mychild locked'>1</div>
</div>
<div class='myparent'>
    <div class='mychild locked'>2</div>
</div>
<div class='myparent'>
    <div class='mychild'>3</div>
</div>
Run codeHide result
0
source

jquery filter filter myparent, locked :

$('.myparent').filter(function(){
  return !$(this).find('.locked').length;
}).css('color','blue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='myparent'>
    <div class='mychild locked'>one</div>
</div>
<div class='myparent'>
    <div class='mychild locked'>two</div>
</div>
<div class='myparent'>
    <div class='mychild'>three</div>
</div>
Hide result
0

Source: https://habr.com/ru/post/1683000/


All Articles