I am facing an issue where I want to modify the appearance of an element in an HTML page using CSS and then immediately check its visual properties. However, the changes specified in the CSS are not applied instantly, but rather after a delay.
CSS:
.node {
width: 10px;
}
JavaScript:
// Creating an element
var item = document.createElement("div");
item.className = "node";
document.body.appendChild(item);
console.log(item.clientWidth);
When logging the clientWidth as shown above, the expected output should be 10, yet it returns NaN if requested right away (but does show 10 after a brief delay).
Attempting to use getComputedStyle() produces similar outcomes:
var style = getComputedStyle(item);
console.log(item.style);
The initial result is an empty string, which later corrects itself to "10px" after a short pause.
I believe I may need to wait for the browser's re-layout before accessing the property. Is there a way to prompt the browser to calculate the dimensions of the element without delays? Or perhaps that would not be recommended; is there a direct method to retrieve the width property from the CSS?
In other words, what would be the most effective approach in this situation?
Note: I am attempting to refrain from utilizing jQuery or any additional libraries here.