1

i need to remove some elements if no children...

this will work...

$$('*').each(function() {
    ($$(this).text().trim() === '') && $$(this).remove()
});

but it will look for all elements... i need to limit to some elements.. so i made this..

elements.forEach(element => {
    $$(element).each(function() {
        ($$(this).text().trim() === '') && $$(this).remove()
    });
})

but it doesn't work..

Rajesh
  • 24,354
  • 5
  • 48
  • 79
karina
  • 727
  • 2
  • 9
  • 16

5 Answers5

4

You can use :empty pseudo selector to collect all the empty elements:

$(':empty').remove(); // removes all the empty elements 

If you target some specific elements then either give it a class name and use both in conjuction:

$('.theClass:empty').remove(); 

Or just use the tagnames of specific elements:

$('div:empty').remove(); // removes all the empty divs
Jai
  • 74,255
  • 12
  • 74
  • 103
2

You can use the id, classor tag in the jQuery selector. Try the following way:

$("div:empty").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div><span>test</span></div>
<div></div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

I like Mamun's approach. If you want to apply it on a certain collection of element types only you could modify/simplify it as such:

$("div,td,p,... and other elements").filter(":empty").remove();

Sorry, just noticed, that Jay also provided a part of my solution. I did not want to repeat things unecessarily here, but maybe the combination of the two is still relevant.

Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
0

Remove all empty tags from current document

$("*:empty").remove();
Sumon Sarker
  • 2,707
  • 1
  • 23
  • 36
0

If I understood correctly what you asked, you should rty :

if($("some selection").children() === undefined){
//do something
}

or as a function :

function rmIfNoChild(jQobj){
    if(jQobj.children() === undefined){
      //do something
    }
}
Vivick
  • 3,434
  • 2
  • 12
  • 25