20

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

but works fine in IE , any ideas please ?

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
Mahmoud Farahat
  • 5,364
  • 4
  • 43
  • 59

4 Answers4

19

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.

Chris Prince
  • 7,288
  • 2
  • 48
  • 66
user113716
  • 318,772
  • 63
  • 451
  • 440
  • @Patrick dw : thnx for ur reply and useful info. , do u have any idea about how to make this condition works in FireFox ?? – Mahmoud Farahat Sep 09 '10 at 13:34
  • 1
    @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. – user113716 Sep 09 '10 at 13:37
  • 2
    var str=element.innerHTML(); str = str.replace(/^\s*|\s*$/g,""); if (str == "") { alert('I'm so brilliant'); } – Tomas Narros Sep 09 '10 at 13:38
  • 4
    @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. – user113716 Sep 09 '10 at 13:43
  • @all : thnx for your great support :) – Mahmoud Farahat Sep 09 '10 at 13:50
8

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
  • 11,856
  • 6
  • 53
  • 77
7

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
  • 32,681
  • 5
  • 61
  • 85
1

For me, it seemed like setting my innerHTML was not working in Firefox nor Chrome but it did work in IE because of my error. It turned out that I was never getting the element using getElementById in the first place. IE seems to do just fine with elements which are defined with name= with getElementById but Firefox and Chrome was more stringent and accepts only id= elements. (More correctly in my view) I hope this saves somebody some frustration.
Why does IE do these sorts of things and confuse people...

bipen
  • 36,319
  • 9
  • 49
  • 62
Third
  • 21
  • 6