Is window.getComputedStyle not functioning as anticipated?

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.

Answer №1

Check out the Mozilla Developer Network

The result received is a dynamic CSSStyleDeclaration object that stays up to date as the element's styles undergo changes.

Emphasize the term dynamic.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can Vuejs delay the calculation of a computed property until the component is "ready"?

Within my Vue.js application, I have a `computed` property that relies on a value fetched from an AJAX call. I am looking for a way to delay the calculation of this `computed` property until after the `ready` method has completed. While everything is fun ...

Secure login using AngularJS

I am in need of modifying the code on this Plunker: plnkr.co/edit/Mvrte4?p=preview I want to remove user roles so that all users have access to the same page. If possible, I would like the modified code to be split into two pages: Page 1: index.html co ...

Is there a way to identify and count duplicate data-items within an array, and then showcase this information using a react view?

If we have an array like this: [{id: 1, name: "chocolate bar"}, {id:2, name: "Gummy worms"}, {id:3, name:"chocolate bar"}] Is there a way to show on the dom that we have "2 chocolate bars and 1 Gummy Worms"? ...

Managing State Changes with Redux

Reducers in Redux are primarily designed to be pure functions that take the previous state and an action as arguments, and return a new state object without mutating the previous state. However, it is still possible for developers to directly mutate the st ...

Uncovering design elements from Material UI components

The AppBar component applies certain styles to children of specific types, but only works on direct children. <AppBar title="first" iconElementRight={ <FlatButton label="first" /> }/> <AppBar title="second" iconElementRight={ <di ...

How can we efficiently retrieve newly submitted JSON data using AJAX?

Is there an efficient way for a user to input a number, submit it, and have it update a JSON page without refreshing the entire webpage? Can this be achieved using an ajax call? The code below retrieves game data, but I want it to update when the user su ...

The new Facebook login button in my app seems to be glitchy as it fails to redirect users to the appropriate page after

I am working on a web application and have successfully integrated Facebook login from developers.facebook.com. However, I am facing an issue where after the user logs in with their Facebook credentials, they are not redirected to my application. Additiona ...

Edit the settings for the dual-axis line chart's parameters

After countless hours of scouring the Internet and numerous attempts, I have come to the decision to seek help by posting my issue on this forum. I must confess, I am not the best developer. My approach usually involves finding pre-existing code that I ca ...

"Why is it that only one of the two similar spans with onclick event is not functioning properly

Encountering a perplexing issue that has me stumped. Here's the code in question: js: function Test() { alert("test"); } html: <span id='bla' onclick='Test()'> Click me </span> <hr> <span id='bla2& ...

Exploring the main directive flow, attaining access to `ctrl.$modelView` in AngularJS is

Four Methods Explained: What Works and What Doesn't I recently created an angular js directive where I encountered difficulty accessing the ctrl.$modelValue in the main flow. In my quest to find a solution, I came up with four potential methods, eac ...

What is the best approach for dynamically appending new elements to a JSON array using PHP?

I am facing an issue with the JSON below: [{"username":"User1","password":"Password"}, {"username":"User5","password":"passWord"},] The above JSON is generated using the PHP code snippet mentioned below: <?php $username = $_POST["username"]; ?>&l ...

emptyQueue in jQuery

I'm currently working with a jQuery script that takes the src of an image, places it in a hidden div, and enlarges the image with an animation when hovering over the requested image. However, I've encountered an issue where the clearQueue or stop ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

Browser-based Javascript code execution

I've been pondering this question for a while now, and I can't seem to shake it off. I'm curious about how JavaScript is actually processed and executed in a web browser, especially during event handling scenarios. For instance, if there are ...

Effective strategies for organizing component features in React

As I was reading through the React documentation, I came across the idea that using React effectively involves following the Single Responsibility Principle, meaning each component should have a specific purpose. I've already created a basic Gameboard ...

Working with JSON structure using Javascript

I successfully transformed an XML file into a JSON format, but now I need to manipulate the data in order to achieve a specific desired structure. Here is the Original format { "machine": "Hassia2", "actual_product_date": "08/24/2017", "holdi ...

Child component not receiving disabled state from Angular 8 FormControl

In my code, there is a unique custom input that I have defined: <nivel-servico-slider formControlName="fornecedor_a"></nivel-servico-slider> This custom input has all the necessary properties as outlined in Angular's guide for c ...

Why does this element on Safari have a focus outline appearing even before it is clicked?

The issue is occurring specifically in Safari, and you can see it firsthand by clicking the "chat now" button located in the lower right corner of the screen: Upon clicking the "chat now" button, the chat window's minimize button displays a focus out ...

How do I utilize Ajax to compare the value selected from a drop down menu in a form with entries in my database, and retrieve the corresponding record/row to automatically fill in a form?

I have a drop-down menu where users can select an option. I need to match the selected value with the corresponding record in my database under the "invoiceid" column, and then populate a form with the associated data when a prefill button is clicked. Belo ...

Display information in a paginated format using components

As a newcomer to React, I may use the wrong terms so please bear with me. I am attempting to implement pagination for an array of components. To achieve this, I have divided the array into pages based on the desired number of items per page and stored eac ...