0


I have the next simple html: <td id="comment_td"> </td>. There are two spaces in td. I check the td html like this:

if (!$('#comment_td').html()) {
    $('#comment_td').html('No Comments');
}

But it works only in IE))) In Firefox this condition is not perform. Can you help me?

John Hartsock
  • 85,422
  • 23
  • 131
  • 146
Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143
  • because then the problem would be reversed, it will work in FF but not IE, as IE will transform `' '` in `''` – RobertPitt Nov 23 '10 at 18:34

5 Answers5

2

If you are trying to see if the is empty of all content, you may want to trim any spaces from it.

if($('#comment_td').html().trim().length == 0) {
    $('#comment_td').html('No Comments');
}

Some browsers remove duplicate spaces, and may even remove all spaces between two tags if there is no other content.

If you wish to check if there are spaces, you should really output the spaces using the &nbsp; character, like this:

<td id="comment_td">&nbsp;&nbsp;</td>
Greg
  • 21,235
  • 17
  • 84
  • 107
2

Try the following:

var Comment = $('#comment_td');
if(Comment.html().trim().length == 0)
{
    Comment.html('No Comments');
}

By checking the trimmed length your specifically stating to remove white space, as some browsers like IE will remove white space where as others will not, so in firefox because theres a space in the element its actually exists.

If your comments within the comments_td are in containers then you can also check the children, for example:

<td id="comment_td">
   <p class="comment">A comment</p>
   <p class="comment">A comment</p>
</td>

Then within jQuery you can do:

if($("#comments_td > p.comment").size() == 0)
{
   //No Comments.
}
RobertPitt
  • 56,863
  • 21
  • 114
  • 161
1
if ($('#comment_td').html().trim() == "") {
    $('#comment_td').html('No Comments');
}
hunter
  • 62,308
  • 19
  • 113
  • 113
0
var empty = $.trim( $('#comment_td').html() ).length == 0;

if ( empty ) {
  // do whatever
}
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
0
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

And

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">

render both of above differently under firefox.

This might be related to your !DOCTYPE defined on the very first line of your HTML document, before HTML tag. Read more about these Mysterious Gaps.

Community
  • 1
  • 1
Ramiz Uddin
  • 4,249
  • 4
  • 40
  • 72