Ujjawal Bhandari
Ujjawal Bhandari

Reputation: 1372

Remove class based on multiple conditions

I want to remove whole div when it contains both .section.level3 and .tutorial-question classes. When I use $('.section.level3 .tutorial-question').eq(0).remove(); it ignores tags (like h3 below) between these two classes. I want h3 to removed as well (refer html below).

I can't simply use .section.level3 as it would remove other divs that contain only .section.level3. I want div to be removed based on both .section.level3 and .tutorial-question Codepen link for reference

$('.section.level3 .tutorial-question').eq(0).remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="section level3">
  <p>Testing</p>
</div>

<div class="section level3">
  <h3>Multiple Choice Questions</h3>
  <div class="tutorial-question">
    <div class="radio">
      <label>
        <input type="radio" name="q9-answer" value="8 15 12 (with some warning)">
        <span>8 15 12 (with some warning)</span>
      </label>
    </div>
  </div>
</div>

Upvotes: 0

Views: 95

Answers (2)

mplungjan
mplungjan

Reputation: 177940

Find it and remove the closest .section

$('.section.level3 div.tutorial-question').each(function() {
  $(this).closest('.section').remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="section level3">
  <p>Testing</p>
</div>

<div class="section level3">
  <h3>Multiple Choice Questions</h3>
  <div class="tutorial-question">
    <div class="radio">
      <label>
        <input type="radio" name="q9-answer" value="8 15 12 (with some warning)">
        <span>8 15 12 (with some warning)</span>
      </label>
    </div>
  </div>
</div>

Upvotes: 2

AmiralBl3ndic
AmiralBl3ndic

Reputation: 416

There is no need for jQuery here:

document.querySelectorAll(".section.level3 .tutorial-question").forEach(el => el.parentElement.remove());
<div class="section level3">
 <p>Testing</p>
</div>

<div class="section level3">
<h3>Multiple Choice Questions</h3>
<div class="tutorial-question">
    <div class="radio">
      <label>
        <input type="radio" name="q9-answer" value="8 15 12 (with some warning)">
        <span>8 15 12 (with some warning)</span>
      </label>
    </div>
      </div> 
</div>

Upvotes: 1

Related Questions