Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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?
};

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top