Home > Net >  Chrome div.clientHeight=0 when innerText or innerHTML = space character
Chrome div.clientHeight=0 when innerText or innerHTML = space character

Time:02-27

I have run into a really strange problem...

When creating a DIV element, I add it to the DOM and set the innerText property to be a single space character. When I check the clientHeight property, it is 0. If I change it to something...say the letter 'a', the clientHeight property changes to 18.

Typed in the console.

aa = document.createElement("div")
<div>​</div>​
aa.clientHeight
0
aa.innerText = ' ';
' '
aa.clientHeight
0
document.body.appendChild(aa);
<div>​ ​</div>​
aa.clientHeight
0
aa.innerText = 'a';
'a'
aa.clientHeight
18
aa.innerText = ' ';
' '
aa.clientHeight
0

I tried the same thing in Firefox and it's doing the exact same thing. Is this part of the standard or what? I'm thinking it may be since Firefox is doing the exactly same thing. I don't have an Apple device so I can't try it in Safari.

I could set the style.height to force it to 18...

Any suggestions or ideas?

CodePudding user response:

HTML uses a behavior called whitespace collapse — browsers will display multiple HTML spaces as one space, and will also ignore spaces before and after elements and outside of elements.

so when you set space as text and nothing else to the div HTML entirely ignores that. To add space you can use HTML Non-Breaking Space(&nbsp;) but since it is not text it is HTML you will have to use innerHTML instead of innerText.

I have created a codepen for you to play around with

https://codepen.io/jaydave1412/pen/qBVMGpe

  • Related