admin管理员组

文章数量:1405366

Neither of the properties clientHeight and offsetHeight has worked out for me while I try to determine the height of the div created dynamically. Could someone suggest alternative please? Thanks a ton in advance.

Neither of the properties clientHeight and offsetHeight has worked out for me while I try to determine the height of the div created dynamically. Could someone suggest alternative please? Thanks a ton in advance.

Share Improve this question asked Oct 12, 2010 at 9:13 user467977user467977 2
  • are you able to use jquery at all?? if so, then it's quite simple. – jim tollan Commented Oct 12, 2010 at 9:15
  • You can write a function to get the distance from your div to the nearest available element above it. Then do the same for the nearest element below it. Then get the distance between those 2 elements (the element above and below the div), then subtract the first 2 values from the last value calculated. In other words... distance between 2 elements - (height above div + height below div) should give you a really close approximation. Depending on how you write the function, you could simply do -> bottom element's distance from top - top element's distance from top. – Shmack Commented Jan 15, 2020 at 22:44
Add a ment  | 

4 Answers 4

Reset to default 2

Ashriya,

if you are able to use jquery, (as an alternative) then you can easily find (and set) the height of any div (in your domain) as such:

// get the height
var myDivHeight = $('#myDiv').css('height');


// set the height
$('#myDiv').css('height', myDivHeight + someothernumber);

hope this helps a 'little'...

[edit] - forgot to use the # id placeholders in my original response. have corrected above!! - argh :)

I'm not a fan of JQuery. I use the "native" mydiv.offsetHeight - works with IE and FF.

I'm not sure, that I pletely understand your problem. However, a following approach may be helpful.

<html>
<body onload="documentReady();">
<script type="text/javascript">
    function documentReady() {
        var div = document.createElement("div");
        div.innerText = "I'm a div, excluded from DOM!";

        var helper = div.cloneNode(true);
        helper.style.position = "relative";
        helper.style.top = "-100000px";
        helper.style.left = "-100000px";
        document.body.appendChild(helper);

        var height = helper.offsetHeight;
        var width = helper.offsetWidth;

        document.body.removeChild(helper);

        alert([height, width]);
    }
</script>
</body>
</html>

Use jQuery's outerHeight().

本文标签: javascriptFind the height of dynamically created divStack Overflow