简体   繁体   中英

remove some elements if no children

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..

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

You can use the id , class or 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> 

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.

从当前文档中删除所有empty tags

$("*:empty").remove();

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM