I often read that changing a style after reading the element's style is a bad practice as it triggers an unnecessary reflow. Consider this code from here:
Bad Code:
elementA.className = "a-style";
var heightA = elementA.offsetHeight; // layout is needed
elementB.className = "b-style"; // invalidates the layout
var heightB = elementB.offsetHeight; // layout is needed again
Good code:
elementA.className = "a-style";
elementB.className = "b-style";
var heightA = elementA.offsetHeight; // layout is needed and calculated
var heightB = elementB.offsetHeight; // layout is up-to-date (no work)
I am curious to know why elementA.offsetHeight
will cause a layout? Here we are simply reading already applied changes, not really applying a change (like in case of elementA.className = "a-style"
).