Get div height with plain JavaScript

前端 未结 10 825
梦毁少年i
梦毁少年i 2020-11-22 17:22

Any ideas on how to get a div\'s height without using jQuery?

I was searching Stack Overflow for this question and it seems like every answer is pointing to jQuery\'

相关标签:
10条回答
  • 2020-11-22 17:39

    Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.

    Example:

    var elem = document.getElementById("myDiv");
    if(elem) {
      var rect = elem.getBoundingClientRect();
      console.log("height: " + rect.height);  
    }
    

    UPDATE: Here is the same code written in 2020:

    const elem = document.querySelector("#myDiv");
    if(elem) {
      const rect = elem.getBoundingClientRect();
      console.log(`height: ${rect.height}`);
    }
    
    0 讨论(0)
  • 2020-11-22 17:39

    The other answers weren't working for me. Here's what I found at w3schools, assuming the div has a height and/or width set.

    All you need is height and width to exclude padding.

        var height = document.getElementById('myDiv').style.height;
        var width = document.getElementById('myDiv').style.width;
    

    You downvoters: This answer has helped at least 5 people, judging by the upvotes I've received. If you don't like it, tell me why so I can fix it. That's my biggest pet peeve with downvotes; you rarely tell me why you downvote it.

    0 讨论(0)
  • 2020-11-22 17:42
    var clientHeight = document.getElementById('myDiv').clientHeight;
    

    or

    var offsetHeight = document.getElementById('myDiv').offsetHeight;
    

    clientHeight includes padding.

    offsetHeight includes padding, scrollBar and borders.

    0 讨论(0)
  • 2020-11-22 17:43
    var myDiv = document.getElementById('myDiv'); //get #myDiv
    alert(myDiv.clientHeight);
    

    clientHeight and clientWidth are what you are looking for.

    offsetHeight and offsetWidth also return the height and width but it includes the border and scrollbar. Depending on the situation, you can use one or the other.

    Hope this helps.

    0 讨论(0)
  • 2020-11-22 17:43

    One option would be

    const styleElement = getComputedStyle(document.getElementById("myDiv"));
    console.log(styleElement.height);
    
    0 讨论(0)
  • 2020-11-22 17:45

    In addition to el.clientHeight and el.offsetHeight, when you need the height of the content inside the element (regardless of the height set on the element itself) you can use el.scrollHeight. more info

    This can be useful if you want to set the element height or max-height to the exact height of it's internal dynamic content. For example:

    var el = document.getElementById('myDiv')
    
    el.style.maxHeight = el.scrollHeight+'px'
    
    0 讨论(0)
提交回复
热议问题