House3272 House3272 - 1 year ago 73
HTML Question

Empty <p> element not actually empty? Ascii Control characters?

Using JavaScript, I'm going through an array of objects. If the object has 1 or more values that are not null or empty, a

element is created and then appended to the container element.

var tempElem = document.createElement("P");

if( item.valueOne !== '' )
tempElem.innerHTML += item.valueOne;
if( item.valueTwo !== '' )
tempElem.innerHTML += item.valueTwo;

if( tempElem.innerHTML !== '' )

The above does filter out most empty entries, however a few are somehow making it through to the page.

On chrome, it shows exactly

I've done some analyzing, and before the last if-statement...

typeof tempElem.innerHTML = string
tempElem.innerHTML.length = 4
tempElem.innerHTML.charCodeAt(0) = 1
tempElem.innerHTML.charCodeAt(1) = 1
tempElem.innerHTML.charCodeAt(2) = 1
tempElem.innerHTML.charCodeAt(3) = 1
tempElem.innerHTML.charCodeAt(4) = NaN

I'm quite lost on this one. The actual data is in json and for these particular values, I'm seeing
. Which is exactly the same as the ones that are being filtered just fine.

I know I can check the values in javascript before creating any kind of dom element, but I'd like to know what's causing this and how to fix it directly.

Answer Source

Turns out it was due to my usage of the .trim() method.
STRING.trim() does not remove characters such as x00 (Start of Header), x01 (Start of Text), etc.
If present in an otherwise empty string however, these characters will still pass a ==="" check.

For my specific purposes, this simple regex fixes the issue:
(will return true if at least 1 non space or 'empty' character exists)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download