1

I have the following class:

<div class='prod-item'>
</div>

I may have multiple versions of this class within the DOM. Is it possible to iterate through each, and remove those with no inner HTML elements?

For example, this can stay:

<div class='prod-item'>
<p>Pussy</p>
</div>

This should go:

<div class='prod-item'>
</div>

I have the following incomplete function, but I'm unsure on how to check if inner elements exist:

$('li[class="prod-item"]').each(function() {
    if(){
     this.removeAttribute('class');
   }
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Liam Fell
  • 1,308
  • 3
  • 21
  • 39
  • What did you try ?? i can think of 2 solutions in a minute :) –  Jun 16 '16 at 09:53
  • Possible duplicate of [Using an if statement to check if a div is empty](http://stackoverflow.com/questions/4665466/using-an-if-statement-to-check-if-a-div-is-empty) – ebram khalil Jun 16 '16 at 09:58
  • `removeAttrribute` will not remove the element, it will only remove it's class. Call `remove()` to remove the actual element. i have posted an answer below – wmash Jun 16 '16 at 10:10

6 Answers6

1

Kind of fast variant:

   $('li[class="prod-item"]').each(function() {
        if($(this).children().length == 0){
         this.removeAttribute('class');
       }
    });
xAqweRx
  • 1,236
  • 1
  • 10
  • 23
1

Use the html() syntax:

$('li[class="prod-item"]').each(function() {
    if($(this).html().length === 0){
     this.removeAttribute('class');
   }
});
connectedsoftware
  • 6,987
  • 3
  • 28
  • 43
1

Filter out all empty div's using filter() method and then remove class using removeClass() method. The html content can get using html() method and check length of the string after removing trailing and leading spaces using $.trim() method.

$('div.prod-item').filter(function() {
  return !$.trim($(this).html()).length;
}).removeClass('prod-item');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='prod-item'>
</div>
<div class='prod-item'>
  <p>Pussy</p>
</div>

<div class='prod-item'>
  <p>Wagon</p>
</div>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

You used LI elements instead of divs...

$('.prod-item').each(function() {
   if ($.trim($(this).html())=='') $(this).removeClass('class'); 
});
Luc Laverdure
  • 1,398
  • 2
  • 19
  • 36
1

You can use

1) empty selector:

$('li[class="prod-item"]:empty').removeClass('prod-item');

2) or not with has selector here:

$('li[class="prod-item"]:not(:has(*))').removeClass('prod-item');
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1
$(".prod-item").each(function() {
   if($(this).children().length == 0) {
     $(this).remove();
   }
});
wmash
  • 4,032
  • 3
  • 31
  • 69