1

Considering the following HTML:

<div style="line-height: 20px;">
    <p style="margin: 0;">Paragraph 1</p>
    <p style="margin: 0;">Paragraph 2</p>
    <p style="margin: 0;">Paragraph 3</p>
</div>

If I change the line-height via Javascript, is it guaranteed that I'll be able to know the new height from the div right away?

Or is it safer to use requestAnimationFrame to make sure the styles are applied and calculated?

const div = document.querySelector("div");
console.log(div.clientHeight); // 60
div.style.lineHeight = "40px";
console.log(div.clientHeight); // 120?
<div style="line-height: 20px;">
    <p style="margin: 0;">Paragraph 1</p>
    <p style="margin: 0;">Paragraph 2</p>
    <p style="margin: 0;">Paragraph 3</p>
</div>

2 Answers2

2

Yes you can be sure you'll get the updated value.

Element.clientHeight, among many other properties and methods will trigger a reflow, a.k.a a recalc so its returned value is up to date.

By the way, triggering a synchronous reflow like this is generally frowned upon because the browser has to recalculate all the boxes in the CSSOM, and on big pages, it can take very long.

Ps: to answer the title question, see this Q/A

Kaiido
  • 123,334
  • 13
  • 219
  • 285
0

You are correct. requestAnimationFrame() is the way to go.

Styles won't be recalculated by the time the following line is run.

Steve Oh
  • 334
  • 3
  • 7