Skip to content
Advertisement

window.getCompuedStyle doesn’t work as expected?

I write following function to return 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 quite confused why after I remove the div, all styles’ property in the computed_styles will become "" nothing, but before I remove the div, all styles’ property in the computed_styles has something different than "".

In my understanding, the value for variable will not be changed and is static unless we write any update or reassign statement once declared (AM I Wrong?)

Why the computed_styles will be automatically update?

Thank you!

P.S: not asking for solution (solution quite easy), but curious why.

Answer

See MDN

Return value: A live CSSStyleDeclaration object, which updates automatically when the element’s styles are changed.

Note the word live.

Advertisement