Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter out '&nbsp' in jQuery?

Tags:

jquery

I am trying to detect if the selected element contains &nbsp only.

For example:

if('td').is(':empty'){
   //do something...
}

The above codes would work if <td><td> but not <td>&nbsp</td>.

What is the best way to filter out the &nbsp?

like image 459
FlyingCat Avatar asked Aug 01 '13 22:08

FlyingCat


1 Answers

You could trim the string representation:

if ($('td').text().trim() == ""){
   //do something...
}

Admittedly, I'm making the rather bold assumption here that in general you don't want any table cell elements devoid of text, regardless of whether this is a case of <td> </td> or <td><span></span></td>.

If the second example is a false positive for your purposes, you can use a stricter version, like so:

var td = $('td');
if ((td.children().length == 0) && td.text().trim() == ""){
   //do something...
}

This ensures the td is not considered a match if it has nodes other than text nodes, regardless of whether it is devoid of text.

like image 61
Asad Saeeduddin Avatar answered Sep 20 '22 13:09

Asad Saeeduddin