comment 0

span innerText empty problem

I had a strange problem using spans in my page
Sometimes, trying to access span’s innerText resulted in an empty string, sometimes it didn’t

The difference I noticed was in the way the script is invoked
The working version occurred on click event of a containing div

The failing version occurred during programatically invocation of the same method from an event of another control

My span was looking like this:

<div class="main front" onclick="alert(this.getElementsByTagName('span')[0].innerText)">
  <span class="text">
      My span 123
      <span class="text">456</span>
  </span>
</div>

With this css class:

.text {
  color: white;
  white-space: pre-line;
  padding-top: 5px;
  visibility: hidden;
  position: absolute;
  left: 0px;
  top: 0px;
  height: 0px;
  width: 100%;
}

The alert invoked in the onclick event fired no text…

Took me few hours to define the problem correctly and once I got it right the solution was sweet and short

I reached this article, summarizing the whole wisdom behind innerText property which appears to have an interesting history of its own.

I got to this paragraph:

Another one is “visibility: hidden”. Similar to “opacity: 0” (and unlike “display: none”), a text is still part of the flow, it just can’t be seen. Common sense would suggest that it should still be part of the output. And while Internet Explorer does just that, WebKit/Blink disagrees (also being curiously inconsistent with their “opacity: 0” behavior).

It pointed exactly to my problem – the span was defined with hidden visibility value, which appears to remove it from its container

Changing the css to opacity: 0 instead of visibility: hidden resolved my problem

Leave a Reply

Your email address will not be published. Required fields are marked *