Results 1 to 2 of 2

Thread: how to get size of DOM element's content

  1. #1
    Join Date
    Oct 2007
    Location
    Germany, Berlin
    Posts
    41
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default how to get size of DOM element's content

    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:
    Code:
    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

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    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.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •