简体   繁体   中英

Javascript: unable to get height of newly created element

After updating the DOM with a new element (ei body.append(html)), I cannot immediately get the height of the newly updated element (eg body.height()). A partial fix is setting a time interval and getting the height at the end of time interval (setTimeout("alert(body.height)", 500)).

Any better ideas? Like a callback after DOM completely updates? Thanks.

Edit: This only happens when there is a lot going on in the background (ie when page first loads). It would seem like the page update is almost instantaneous if nothing else is being processed. What I need is a callback, or an indicator of when the DOM is reformed!

Edit: The problem is from the browser being 'distracted' by other processes, which makes the browser unable to update immediately after the append of the element. How do I fix this?

The timeout method works because the rendering engine is given a chance to display the new element there by giving it a change to render it and thus assigning it a height.

You can set the timeout to 0 and still have the same effect.

With jQuery works fine for me.

In the jsfiddle demo I put the next code:

$(function(){
    var jTest = $('#test');

    console.log('The height:',jTest.innerHeight(),jTest.height()); //Show me 'The height: 20 20'

    jTest.append('<div><br/>How are you?</div>');
    console.log('The height:',jTest.innerHeight(),jTest.height()); //Show me 'The height: 60 60'

});

Unless you mean javascript only solution or put a jsFiddle demo to show your error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM