Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove parent if it doesn't have a child with specific class

I have a code like this:

<div class='parent one'>
  <div class='yes'></div>
  <div class='yes'></div>
  <div class='yes'></div>
</div>

<div class='parent two'>
  <div></div>
  <div></div>
  <div></div>
</div>

<div class='parent three'>
  <div></div>
  <div></div>
  <div class='yes'></div>
</div>

How do I remove .parent.two because it doesn't have any child with .yes? What I've tried so far and it didn't work:

$('.parent div:not(.yes)').remove();
like image 900
Ozik Jarwo Avatar asked Aug 11 '20 16:08

Ozik Jarwo


2 Answers

You can use :not with :has:

$(() => $('.parent:not(:has(.yes))').remove())
.parent{ background: orange; height: 100px; width: 100px; margin: 10px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent one'>
  <div class='yes'>Child of one</div>
  <div class='yes'>Child of one</div>
  <div class='yes'>Child of one</div>
</div>

<div class='parent two'>
  <div>Child of two</div>
  <div>Child of two</div>
  <div>Child of two</div>
</div>

<div class='parent three'>
  <div>Child of three</div>
  <div>Child of three</div>
  <div class='yes'>Child of three</div>
</div>
like image 139
Anurag Srivastava Avatar answered Oct 25 '22 08:10

Anurag Srivastava


You could create a selector as a combination of :not and :has and then use remove method. So this will select all elements with .parent class that do not have child element with .yes class.

$('.parent:not(:has(.yes))')

$('.parent:not(:has(.yes))').remove()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='parent one'>
  <div class='yes'>one</div>
  <div class='yes'></div>
  <div class='yes'></div>
</div>

<div class='parent two'>
  <div>two</div>
  <div></div>
  <div></div>
</div>

<div class='parent three'>
  <div>three</div>
  <div></div>
  <div class='yes'></div>
</div>
like image 31
Nenad Vracar Avatar answered Oct 25 '22 09:10

Nenad Vracar