Here is a function I created to determine the width and height of a text:
function size_calculation(word,fontSize) {
const div = document.body.appendChild(document.createElement('div'));
div.textContent = word;
div.style.cssText = `
font-size:${fontSize}px;
width:auto;
position:absolute;
visibility:hidden;
`
const computed_styles = window.getComputedStyle(div);
//return the expected height
console.log(computed_styles.getPropertyValue('height'))
div.remove();
//return nothing
console.log(computed_styles,computed_styles.getPropertyValue('height'))
return ({
height: computed_styles["height"],
width:computed_styles["width"]
})
}
console.log(size_calculation("hi",15))
I am puzzled by the fact that after removing the div
, all styles' properties in the computed_styles
become empty, whereas before removing the div
, they hold different values.
As far as my understanding goes, variable values should remain static unless explicitly updated or reassigned (or am I mistaken?).
Can anyone explain why the computed_styles
are automatically updating?
Thank you!
P.S: This is not a request for a solution (the solution is quite simple), but rather a curiosity about the behavior described above.