views:

198

answers:

3

why is if (element.innerHTML == "") not working in firefox

but works fine in IE , any ideas please ?

+4  A: 

Hard to say without seeing your HTML, but I'd say probably because you have some empty white space in the element, and IE doesn't treat that as a text node, while FF does.

I believe it is actually a more strict standards compliance to treat any empty white space between tags as a text node, but IE doesn't comply.

You could do:

var htmlstring = element.innerHTML;

  // use the native .trim() if it exists
  //   otherwise use a regular expression
htmlstring = (htmlstring.trim) ? htmlstring.trim() :​ htmlstring.replace(/^\s+/,'');​​​​​​

if(htmlstring == '') {...

Or just get rid of the whitespace in your HTML markup manually.

patrick dw
@Patrick dw : thnx for ur reply and useful info. , do u have any idea about how to make this condition works in FireFox ??
mahmoud
@mahmoud, make the > of the opening tag touch the < of the closing tag...
Benjol
@mahmoud - For browsers that support `.trim()`, you could trim the whitespace before you test. Not all browsers support `.trim()` though. I'll update in a minute.
patrick dw
var str=element.innerHTML();str = str.replace(/^\s*|\s*$/g,"");if (str == "") { alert('I'm so brilliant');}
Tomas Narros
@Tomás - You could actually get rid of the last half of your regex. If the `innerHTML` only has white space, then it is redundant to test the beginning *and* the end of the string.
patrick dw
@all : thnx for your great support :)
mahmoud
@patrick- you're right. Thanks for your comment
Tomas Narros
+3  A: 

You could check if element.innerHTML.trim() == "" for the best results. However, then you have to extend the string prototype with a trim() method:

if (!String.prototype.trim) {
    String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
}

if (element.innerHTML.trim() == "") {
  //do something
}
naivists
This would overwrite any native implementation in browsers that support `.trim()`. You should really test for it first.
patrick dw
@patrick thanks, fixed (I hope so)
naivists
Yep, I think that would cover it. :o)
patrick dw
A: 

An alternative method to check for the empty string is to check the length:

element.innerHTML.length == 0

But, you'd still have to trim() if you had a whitespace string you wanted to match.

palswim