1

Is there a way to use an "if" statement and see if a divs height is larger or smaller than a specific amount of px in javascript?

For example, can you do something like this?:

if (document.getElementById('mydiv').style.height < 50px) {}

I've tried to use 50px, 50, "50px", "50 px"....

Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42

2 Answers2

3

You could use clientHeight or offsetHeight to the get the height of the element and then use it in if statement.

clientHeight

The Element.clientHeight read-only property is zero for elements with no CSS or inline layout boxes; otherwise, it's the inner height of an element in pixels. It includes padding but excludes borders, margins, and horizontal scrollbars (if present).

offsetHeight

The HTMLElement.offsetHeight read-only property returns the height of an element, including vertical padding and borders, as an integer.

Example:

(function() {
        let element = document.getElementById('content');
        if(element.clientHeight < 20) {
          console.log("Client height is less than 20, and height is: ", element.clientHeight);
        } else {
          console.log("Client height is greater than 20", element.clientHeight);
        }
      })();
 <div id="content" style="height: 19px;">Some div</div>
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42
0

var divElement = document.querySelector(".app");       
var elemHeight = divElement.offsetHeight;
var exampleHeight = 60;
if(elemHeight > 60){
  console.log('enough');
 }else{
  console.log('not enough');
}

console.log(elemHeight);
<div class="app">
<p>this is simple text</p>
</div>

elaborate your question clearly. for exact result. I think you want that