Skip to content Skip to sidebar Skip to footer

How To Get (display:none)element Height Using Pure Javascript?

I am trying to get a height of a (display: none) element but it returns 0. But when I am using jquery it returns a valid value using this code. I need it using javascript. We all

Solution 1:

An element with display: none never has height or width. Here's a (non jquery) way to determine it's dimensions. It positions the element temporary absolute outside the viewport and then removes display: none. Now the element's dimensions can be queried. After that the positioning etc. is done in reverse and the height found is returned.

const hiddenEl = document.querySelector("#someEl");
console.log(`display none: ${hiddenEl.clientHeight}`);
console.log(`height determined by method: ${
  determineHeightOfAHiddenDivElement(hiddenEl)}`);

functiondetermineHeightOfAHiddenDivElement(elem) {
  elem.style.position = "absolute";
  elem.style.top = "-5000px";
  elem.style.display = "initial";
  const height = elem.clientHeight;
  elem.style.display = "";
  elem.style.top = "";
  elem.style.position = "";
  return height;
}
.as-console-wrapper { top: 0; max-height: 100%!important; }

#someEl {
  display: none;
  height: 300px;
}
<divid="someEl">You don't see me</div>

Solution 2:

I took a look at the jQuery source. Ignoring the code to handle box-model, different browsers etc, jQuery does the following:

const elm = document.querySelector('.elm');
const styles = window.getComputedStyle(elm);
console.log(parseFloat(styles.height));
.elm{
  height: 300px;
  width: 300px;
  background-color: #007bff;
  
  display: none;
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script><divclass="elm"></div>

Solution 3:

One option is to use window.getComputedStyle(element).

const elm = document.querySelector('.elm');
const computedHeight = window.getComputedStyle(elm).heightconsole.log('Computed height', computedHeight);
console.log('Parsed', parseInt(computedHeight.replace('px', '')))
.elm{
  height: 300px;
  width: 300px;
  background-color: #007bff;
  
  display: none;
}
<divclass="elm"></div>

Another, probably uglier, would be to clone the element, give it a display: block, attach it to the document and get the height off that, destroying the clone right after.

const elm = document.querySelector('.elm');
const clone = elm.cloneNode();
clone.style.display = 'block';
document.body.appendChild(clone);
console.log(clone.clientHeight);
document.body.removeChild(clone);
.elm{
  height: 300px;
  width: 300px;
  background-color: #007bff;
  
  display: none;
}
<divclass="elm"></div>

You could also temporarily give the element itself display: block, then restore the previous style.

The ideal solution would likely depend on the use-case.

Post a Comment for "How To Get (display:none)element Height Using Pure Javascript?"