How to say "Contains nothing" in jQuery?

I want to add the class "foo" to all span tags in a document that does not contain text inside them. How to do it?

+3
source share
2 answers
$('span:empty').addClass('foo');

Just keep in mind that empty-selector (docs) means completely empty, which means spaces.

If you want to allow spaces, do the following:

$('span').filter(function() {
    return !$.trim( this.innerHTML );
}).addClass('foo');

It uses the jQuery.trim() (docs) method inside filter() (docs) to allow elements that have only whitespace content (no elements).

+7
source

This will work:

$('span').each(function() { 
   if ($.trim($(this).text()).length == 0) { 
      $(this).addClass('foo');
   }
});
+1
source

Source: https://habr.com/ru/post/1793459/


All Articles