why would textContent not trigger a reflow
Asked Answered
D

1

6

I was looking at the difference between textContent and innerText on MDN.And it shows me something that confused me a lot.

1.innerText is aware of style and will not return the text of hidden elements, whereas textContent will. (no problem, totally understand)

2.As innerText is aware of CSS styling, it will trigger a reflow, whereas textContent will not. (why?)

Drucilla answered 22/10, 2015 at 8:11 Comment(4)
@Nit May be it's a bit foolish to ask like that.It seems that i have not made a fully understand of reflow yet.I found an article about it: developers.google.com/speed/articles/reflow Now i got it. Anyway, thanks for your suggestion!Drucilla
Now i totally understand it! Since innerText only get visible texts, it should trigger reflow first(flush the queued reflow list) and re-calculating the style of the element.Then get the right result.Drucilla
whereas textContent has not to do that.Drucilla
You might want to specify here that the important part is that reading the innerText causes the reflow, which really surprised me when I learned it the hard way. Now it is obvious even to me, because the engine has to take into account the CSS at the moment of accessing the value, and for this a reflow is triggered.Lager
D
4

I was suggested to answer this question instead of leaving comments. Though I did a lot more research after that. Now let's take a look at the differences again.

innerText is aware of style and will not return the text of hidden elements

Referenced from MDN.

It means, innerText only get text from visible elements(not display: none, nor visibility: hidden). In addition, css styles applied on elements like text-transform: uppercase will also be taken into account. As a result, innerText will return the uppercased version of text while textContent will return the unchanged version. You can have a try of this demo on jsfiddle.

Since innerText needs to know what the most-recent style the element is, it should trigger reflow first (flush the queued reflow list) and re-calculating the style of the element.Then get the expected result.

Whereas textContent have not to do it since it's not aware of style.

If you are interested in more details of differences between innerText and textContent, you can have a read of this article.

Drucilla answered 29/8, 2017 at 7:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.