Get div height with plain JavaScript

Get div height with plain JavaScript

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’s .height().
I tried something like, but it returned nothing, even when my div had its width and height set in CSS.


Solution 1:

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


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

clientHeight includes padding.

offsetHeight includes padding, scrollBar and borders.

Solution 2:


var element = document.getElementById('element');

Solution 3:

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


var elem = document.getElementById("myDiv");
if(elem) {
   var rect = elem.getBoundingClientRect();

Solution 4:

var myDiv = document.getElementById('myDiv'); //get #myDiv

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.

Related:  Generate date from week number in moment.js

Hope this helps.

Solution 5:

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.

Solution 6:

<div id="item">show taille height</div>