1

My JavaScript is unable to get the height of a navigation object height:

<nav id="advanced-nav" class="advanced-nav menu" role="navigation">
  <!-- code here -->
</nav>

The CSS for the navigation object has different heights for desktop and mobile

#advanced-nav{
  height: 2em;
  overflow-y: hidden;
}
@media screen and (min-width: 30em) {
  #advanced-nav{
    height: 10em;
  }
}

My JavaScript needs to get the height of the nav object. I'm wondering why the console log is showing an empty string. How do I get the height?

const advanced_nav = document.querySelector('#advanced-nav');
console.log('height',advanced_nav.style.height);
Jun Dolor
  • 609
  • 2
  • 11
  • 25
  • 1
    sometimes you have to use [getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) to get accurate size/position information. This forces the browser to do a page flow/reflow, which may not have happened for the first time yet when you're running your code. However it should be used with care because it does force a reflow, which for large pages can be relatively costly. – David784 Aug 18 '19 at 15:07
  • Thanks, I'm going over it right now. It does look like the better approach to take – Jun Dolor Aug 18 '19 at 15:09
  • See https://stackoverflow.com/a/294273/1886206 – ifthenelse Aug 18 '19 at 15:14
  • advanced_nav.offsetHeight – tehila Aug 18 '19 at 15:19

1 Answers1

1
console.log('height',advanced_nav.offsetHeight);

This will give you the real height in pixels.

If you want the css value:

const advanced_nav = document.querySelector('#advanced-nav');
let computed = window.getComputedStyle(advanced_nav, null);
console.log('height',computed.getPropertyValue('height'));
tom
  • 9,550
  • 6
  • 30
  • 49