javascript - Get height of dynamically created element - Stack Overflow

admin2025-04-20  0

I created one div dynamically and tried to get its height. I didn't assign fixed height to it. But its content is assigned a fixed height. So I tried to get its render height.

$(function(){
    $services = $(<div id="services"></div>);
    $img  = $(<img src="abc.jpg" height="100px" width="100px">);
    $a = $("<a href="home.php">Go to home</a>");
    $services.append($img,$a);
});

$(function(){
    var height = $("#services").height();
});

I got value of height as 0.

So I can't render height of div#services.

I created one div dynamically and tried to get its height. I didn't assign fixed height to it. But its content is assigned a fixed height. So I tried to get its render height.

$(function(){
    $services = $(<div id="services"></div>);
    $img  = $(<img src="abc.jpg" height="100px" width="100px">);
    $a = $("<a href="home.php">Go to home</a>");
    $services.append($img,$a);
});

$(function(){
    var height = $("#services").height();
});

I got value of height as 0.

So I can't render height of div#services.

Share Improve this question edited Nov 30, 2012 at 7:04 Ted Hopp 235k48 gold badges411 silver badges532 bronze badges asked Nov 30, 2012 at 6:59 john markerjohn marker 411 silver badge8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You need to add the element to the DOM before measuring it:

$('body').append($services);
var height = $("#services").height(); // works now

If you need its height before making it visible, a mon trick is to add it to the DOM hidden, measure it, and then make it visible.

You should show those Dom Elements to Page first!

in your case, $services is not shown to the Page, so the result $("#services") will get nothing.

try to do this:

$(function(){
    $services = $(<div id="services"></div>);
    $img  = $(<img src="abc.jpg" height="100px" width="100px">);
    $a = $("<a href="home.php">Go to home</a>");
    $services.append($img,$a);

    //here
    $("body").append($services);
});

it will works.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745114258a285768.html

最新回复(0)