Mahmoud Farahat
Mahmoud Farahat

Reputation: 5485

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

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

but works fine in IE , any ideas please ?

Upvotes: 20

Views: 46985

Answers (4)

user113716
user113716

Reputation: 322572

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.

Upvotes: 19

Third
Third

Reputation: 21

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

Upvotes: 1

palswim
palswim

Reputation: 12140

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.

Upvotes: 8

naivists
naivists

Reputation: 33541

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
}

Upvotes: 7

Related Questions