views:

68

answers:

2

Suppose I dynamically create a DIV using document.createElement, add some inner text, and want to determine its height and width. I can see that before adding the DIV to the DOM tree, properties such as offsetWidth and offsetHeight are 0, which is expected. Once it is programmatically added to the tree, can I expect those properties to be immediately "ready", or are there environments where repaint/reflow may be delayed and occur later?

textDiv = document.createElement("div");
textDiv.innerHTML = "some dynamically created string";
console.log(textDiv.offsetWidth); // 0
document.body.appendChild(textDiv);
console.log(textDiv.offsetWidth); // OK?

I think the answer would be something like "the JavaScript interpreter is single-threaded and the repaint/reflow event triggered by appendChild is part of that thread and finishes before continuing on to the next statement"... but can someone check my understanding?

This Opera article has a lot of what I'm looking for but it's not clear how Opera-specific it is. In any case it does seem like the application developer can assume any required repaint/reflow correctly occurs when taking measurements such as by accessing offsetWidth.

A: 

As far as i know, they are readable only after they are added to DOM tree after all javascript functions or properties work on elements that are already there in the DOM tree.

I tried both cases and following turned out to be working fine:

<SCRIPT>
window.onload = function() {
textDiv = document.createElement("div");
textDiv.innerHTML = "some dynamically created string";
alert(textDiv.offsetWidth); // 0
document.body.appendChild(textDiv);
alert(textDiv.offsetWidth); // OK?
};

Sarfraz
Those alerts could themselves affect the rendering. Try it with `console.log` and Firebug instead.
Tim Down
+1  A: 

As soon as your element is added to the DOM, it should be available for access as if it were there from the beginning. Plain, simple DOM manipulation is synchronous.

Be careful when you start introducing timeouts, intervals, and Ajax.

Christopher Parker
My question is more whether the repaint/reflow that would change the dimension completes by the time I do the offsetWidth. Anyway, it seems like this can be safely assumed to be the case; the repaint/reflow can be considered part of the same thread of the JavaScript execution. I'll go ahead and accept this.