How to remove the parent div if has only an h3 element and empty content divs

Viewed 140

I have a div with a class .tour_head1 and there's always an h3 element and many div with content. I want to check if the tour_head1 has only h3 element and divs with no content, then remove the whole div .tour_head1

HTML

<div class="tour_head1">
  <h3>Description</h3>
     <div> <p>&nbsp;</p> </div>
       <div></div>
 </div>

JQuery

$('.tour_head1:has(h3:only-child)').filter(function() {
  return !this.textContent.trim();
}).remove();
});
2 Answers

You have to check that there's a nested div that's not empty:

$('.tour_head1:has(h3)').each(function() {  // :has(h3) may not be necessary
    if (!$(this).find('div').not(':empty').length) {
        $(this).remove();
    }
});

Fiddle demo

To check text values as well (for cases where there are empty child elements present), do this:

$('.tour_head1:has(h3)').each(function() {
    let contentFound = false;

    $(this).find('div').each(function() {
        if ($(this).text() !== '') {
            contentFound = true;
        }
    });

    if (!contentFound) {
        $(this).remove();
    }
});

Fiddle demo 2

try this with jquery remove

<div class="tour_head1">
  <h3>Description</h3>
     <div> <p>&nbsp; some text</p> </div>
       <div></div>
 </div>
 <div class="tour_head1">
  <h3></h3>
     <div> <p>&nbsp; some text 2</p> </div>
       <div></div>
 </div>
 <div class="tour_head1">
  <h3>Description</h3>
     <div> <p>&nbsp; some text</p> </div>
       <div></div>
 </div>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
 <script>
 $(document).find('.tour_head1').find("h3").each(function(){
  console.log($(this).text());
  if($(this).text() == "" || $(this).text() == null)
  {
    $(this).remove();
  }
});
 </script>

Related