CSS - select element without text inside

2019-06-15 18:23发布

问题:

Is there any way to select some element that have no text inside?

What it mean:

Lets say we've got such elements

<div class="to-select"></div> <-- this is empty
<div class="to-select"><span></span></div> <-- this is not empty, but dont have text

Both of them dont have text, however only one of them is empty and can be selected with :empty. I want both of them to be selected as they dont have text.

Also, some elements might have only white-space text that came from tabbed html markup etc.

I know it's quite easy to do with js. But I'm looking for css solution if it's possible. I dont like to use js for this kind of problems.

回答1:

Indeed, there isn't a selector for elements with no text node children (or descendants).

In Selectors level 4 it may be possible with

.to-select:not(:has(:not(:empty)))

or, to account for inter-element whitespace,

.to-select:not(:has(:not(:blank)))

but since :has() may not be fully available in the fast profile, you may not be able to use it in CSS even once Selectors level 4 is implemented.

Using JS is your best bet, unfortunately. The above selector with :empty will work in jQuery today, but even once :has() is implemented natively, for this specific use case you'd only be able to use it in document.querySelectorAll() at best.



回答2:

You may try this in your CSS:

.to-select:empty {
    <<your attributes>>   
}

.to-select *:empty {
    <<your attributes>>    
}


回答3:

Try this,

$(".to-select").filter(function(){
    return ($(this).text().trim() == "")
})