Get div height with plain JavaScript

前端 未结 10 907
梦毁少年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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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}`);
    }
    

提交回复
热议问题