Alex Pliutau
Alex Pliutau

Reputation: 21957

jquery javascript strange behavior in .html()


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?

Upvotes: 0

Views: 169

Answers (5)

RobertPitt
RobertPitt

Reputation: 57268

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

Upvotes: 2

hunter
hunter

Reputation: 63512

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

Upvotes: 1

Ramiz Uddin
Ramiz Uddin

Reputation: 4259

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

Upvotes: 0

Greg
Greg

Reputation: 21899

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>

Upvotes: 2

meder omuraliev
meder omuraliev

Reputation: 186562

var empty = $.trim( $('#comment_td').html() ).length == 0;

if ( empty ) {
  // do whatever
}

Upvotes: 0

Related Questions