Reahreic
Reahreic

Reputation: 629

Unable to detect empty paragraph

I am using the following code to check for an empty paragraph but it never returns true. Why?

var isEmpty = pageChildren[i].outerHTML.toUpperCase() === "<P></P>";
var isSpace = pageChildren[i].outerHTML.toUpperCase() === "<P> </P>";
var isNbsp = pageChildren[i].outerHTML.toUpperCase() === "<P>&NBSP;</P>";
if(!isEmpty && !isSpace && !isNbsp){
   //do something
}else{
   //do something else
}

This is a copy paste of what IE8 debug tools tells me is in the outerHTML: "<P></P>"

This is being read from an iFrame so i need to remove the <p></p> tags also as the function above this triggers off of the number of children elements in the body of the frame.

Additionally this runs in an HTA application on IE only. The userbase/configuration is highly controlled.

Upvotes: 2

Views: 1980

Answers (3)

Alohci
Alohci

Reputation: 82986

It seems that IE < 9 prepends a carriage return, line feed to the outerHTML result, so for example pageChildren[i].outerHTML.toUpperCase() === '\r\n<P></P>' returns true for an empty p element.

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

If you're sure your object is a paragraph, you should use innerHTML instead :

var isEmpty = pageChildren[i].innerHTML.trim().length==0;

(note that the MDN proposes a replacement for IE8 which lacks trim).

You could also use textContent but the downside is that you have to do a different test for IE.

Upvotes: 4

James Hill
James Hill

Reputation: 61812

Since trim() isn't supported by all browsers, I suggest removing all spaces with RegEx:

var isEmpty =
    (pageChildren[i].innerHTML.replace(/\s/g, '').length == 0) ? true : false;

Upvotes: 1

Related Questions