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
  • 22,581
  • 5
  • 41
  • 70
karina
  • 597
  • 2
  • 7
  • 15

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
  • 72,925
  • 12
  • 73
  • 99
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
  • 62,450
  • 9
  • 45
  • 52
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
  • 21,569
  • 2
  • 21
  • 42
0

Remove all empty tags from current document

$("*:empty").remove();
Sumon Sarker
  • 2,526
  • 1
  • 22
  • 33
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
  • 2,452
  • 2
  • 10
  • 23