The safest way is to find all the text nodes and compare their nodeValue to exactly what you're looking for and remove the ones that contain only whitespace. Doing operations on the innerHTML directly is fraught with difficulties because you have to make sure you aren't messing up things inside the actual tags (e.g. whitespace that is supposed to be there). Operating on the text nodes only uses the browser to keep you safe. You can find all the text nodes that match your condition like this:
$("#foo").contents().filter(function() {
if (this.nodeType == 3) {
return(this.nodeValue.replace(/\s| /g, "") == "");
}
return(false);
}).remove();
You can see it work here: http://jsfiddle.net/jfriend00/RNTbT/
FYI, this version will even handle text nodes that are a combination of whitespaces and
. It works by removing all whitespace and
and then seeing if there's anything left. If not, then it's a whitespace-only text node so it should be removed.