I’m trying to change an element on an HTML page using CSS and then immediately read its visual properties. The CSS-enforced style isn’t applied until later (next ‘frame’), however.
CSS:
.node {
width: 10px;
}
JavaScript:
// Create element
var element = document.createElement("div");
element.className = "node";
document.body.appendChild(element);
console.log(element.clientWidth);
The output of the log call above should be 10, but it’s NaN if called immediately (but it is correctly read as 10 after a frame).
Using getComputedStyle() gives similar results:
var style = getComputedStyle(element);
console.log(element.style);
The output is “” at first run, but “10px” (correctly) after the first frame.
I’m assuming I have to wait once for the browser’s re-layout until I can read the property. Is there a way to force the browser to calculate that element’s dimensions? Or maybe that would be bad practice; is there a straightforward way to read the CSS’s width property?
Put other way, what’s the best practice here?
Notes: trying to avoid using jQuery or other libraries here.
Try accessing the
computedStyleinstead.and then read
Example: http://jsfiddle.net/mGCT5/1/