How to say "Contains Nothing" in jQuery?
I want to add the class "foo" to all span tags on a document that do not have a开发者_开发知识库ny text inside them. How to do this?
$('span:empty').addClass('foo');
Just keep in mind that the empty-selector
(docs) means absolutely empty, meaning no spaces.
If you want to allow for whitespace, do this:
$('span').filter(function() {
return !$.trim( this.innerHTML );
}).addClass('foo');
This uses the jQuery.trim()
(docs) method inside the filter()
(docs) method to allow for elements that have only whitespace content (with no elements).
This would work:
$('span').each(function() {
if ($.trim($(this).text()).length == 0) {
$(this).addClass('foo');
}
});
精彩评论