PDA

View Full Version : how to get size of DOM element's content



ReMaX
04-30-2008, 02:32 AM
Heyho,

I just put myself the question if it is possible to get the size of a DOM element that is not yet appended to the document. There is a content inside and normally the element resizes itself to the size of the content. How do I get this without placing it in the document, reading its size and deleting it?
example:


var element = document.createElement("div");
var element1 = document.createElement("div");
var textnode = document.createTextNode("Hello, you, I am a node!");
element1.appendChild(textnode);
element.appendChild(element1);

alert(element.offsetWidth); // of course, that does not work but how then


greetings
Max

jscheuer1
04-30-2008, 04:16 AM
I really don't think that there is any way to do what you are suggesting. However, there shouldn't be any need to either. If you need the element's width (or height, or any property that it can't have until appended to the document somewhere), you cannot have it before the element is appended to the document. This is because its properties of that sort are defined by where it is appended and by the styles, if any, that apply to it in that location. These will also be influenced by the particular browser and system that the document is being viewed with. So in short, these properties are truly meaningless before the element is appended. But, if you aren't going to append the element, you shouldn't need them.

You could keep the element's display:none or (perhaps a better choice in many cases) its visibility:hidden briefly during the process of appending it, so that its dimensions or whatnot can be ascertained and acted upon before revealing it to the user.

Another strategy that I've used on occasion is to either make or hard code an (for all practical purposes) identical element off screen (position:absolute;top:-1000px;left:-1000px), and use it for getting what you need before proceeding with the 'real' element. This is especially useful if - say, you are also creating a container for the new element that must fit snugly around it while also including another element or elements of fixed dimensions - like a video, as happens to be the case for which I've done things like this.