开发者

How to say "Contains Nothing" in jQuery?

开发者 https://www.devze.com 2023-02-12 01:19 出处:网络
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\');

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');
   }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号