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?

1
  • because then the problem would be reversed, it will work in FF but not IE, as IE will transform ' ' in '' Commented Nov 23, 2010 at 18:34

5 Answers 5

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>
Sign up to request clarification or add additional context in comments.

Comments

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.
}

Comments

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

1 Comment

why not just: $('#comment_td').html().trim() ?
0
var empty = $.trim( $('#comment_td').html() ).length == 0;

if ( empty ) {
  // do whatever
}

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.