Explain Codes LogoExplain Codes Logo

Get div height with plain JavaScript

javascript
prompt-engineering
functions
getBoundingClientRect
Anton ShumikhinbyAnton Shumikhin·Nov 8, 2024
TLDR

Fetch a div's height using element.clientHeight for content height, or element.offsetHeight for total visible height. Here you go:

var height = document.getElementById('yourDivId').clientHeight; // No scrollbar included
var height = document.getElementById('yourDivId').offsetHeight; // Scrollbar's in the party

Don't forget to replace 'yourDivId' with your div's actual ID.

The clientHeight and offsetHeight demystified

Dive deeper into clientHeight and offsetHeight.

Using clientHeight

The clientHeight property gives you the height of the element plus its vertical padding. In essence, it holds a placard that screams, "Padding is in, borders and scrollbars are not!" Usage:

const classyDiv = document.querySelector('.yourDivClass'); // Select div with class console.log(classyDiv.clientHeight); // Ouputs height gracefully ignoring scrollbar and borders

The offsetHeight way

offsetHeight, on the other hand, is the party animal. It includes the clientHeight, the party crasher (i.e., scrollbar), and the bouncer (i.e., border). To use:

const idyDiv = document.getElementById('yourDivId'); // Selecting the div with ID console.log(idyDiv.offsetHeight); // Outputs total height, the whole party!

Shapeshifting divs and computed styles

Transformations and computed styles can put a spin on an element's dimensions. Here's a sneak peek:

Upping the game with getBoundingClientRect()

When you need to consider content transformations, peek into the mystery box using getBoundingClientRect(). But remember, it plays the silent game with hidden elements (display: none).

const currentReality = ele.getBoundingClientRect(); // Summoning Doctor Strange console.log(currentReality.height); // Outputs height in the Mirror Dimension

Total height with getComputedStyle()

When you need the full picture (margins included), call in the window.getComputedStyle() SWAT team:

const allSeeingEye = window.getComputedStyle(ele); // Bringing in S.H.I.E.L.D console.log(allSeeingEye.height); // Featuring: The Total Height

Scrolling height and alternative selectors

For dynamic content and unique selectors, dig into scrollHeight and CSS selectors.

Observing dynamic heights with scrollHeight

When your div is the ever-growing beanstalk (dynamic content), the scrollHeight acts as your golden goose:

console.log(ele.scrollHeight); // Magic beans in action

Say hello to querySelector

When your div plays hide and seek (i.e., lacks an ID), catch it with document.querySelector based on any CSS selector:

const elusiveDiv = document.querySelector('.yourDivClass');

Digging into special cases

CSS properties love to meddle with dimension calculations. Here are a few special cases you should keep your eye on.

border-collapse in action

When dealing with stubborn tables and their border-collapse: collapse stunt, be ready for a slight shift in your measurements:

table { border-collapse: collapse; }

The shapeshifter: Transformed elements

CSS transformations are like the werewolves of elements, affecting their measurements. In such cases, bank on getBoundingClientRect():

const transformedHeight = ele.getBoundingClientRect().height; // Behold the werewolf!

Bring it all together

Perfecting dimension retrieval isn't a walk in the park, but hopefully, with these notes, you've got some solid ground to stand on. Let's round it up!

  • Verify visibility: Hidden elements might return different values.
  • Pseudo-elements: These stylish folks may not impact the measurables.
  • Window resizing: Windows are fickle. Keep an ear to the ground with event listeners:
window.addEventListener('resize', function() { console.log(ele.clientHeight); // "Resize Resistance", every superhero needs a soundtrack });
  • Go live! Always test in a live environment (like a jsFiddle) to see your code in action.
  • Lastly, remember, we are JavaScript natives! We don't need no jQuery to measure dimensions.