Are element sizes easy to read after adding it to the DOM tree?

Suppose I dynamically create a DIV using document.createElement , add some inner text and want to determine its height and width. I see that before adding a DIV to the DOM tree, properties like offsetWidth and offsetHeight are 0, which is expected. After it is programmatically added to the tree, can I expect these properties to be immediately โ€œreadyโ€ or there are environments where repaint / reflow can 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 will be like "the JavaScript interpreter is single-threaded, and the repaint / reflow event raised by appendChild is part of this thread and ends before moving 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 specific it is to Opera. In any case, it seems that the application developer can assume that any required redraw / reflow occurs correctly when taking measurements, for example, by referring to offsetWidth.

+4
source share
2 answers

Once your element has been added to the DOM, it should be available for access, as if it were there from the very beginning. The usual simple DOM manipulation is synchronous.

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

+1
source

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

I tried both cases, and after that it turned out to work 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? }; 

0
source

Source: https://habr.com/ru/post/1300140/


All Articles