0

When I click on a button, I want to increment a div height by 25%, so I would like to be able to get the last div height value as a % and simply add 25 to this.

Is there a javaScript method that would return '80%' which is the height define in the CSS, and not return the calculated px value of the element at 80%?

<div class="container">
</div>

html, body {
  margin: 0;
  height: 100%;
  width: 100%;
}

.container {
  height: 80%;
  background: #eee;
}

let container = document.querySelector('.container');

console.log(container.style.height); //Empty
console.log(container.clientHeight); //Calculated px value at 80%
//I am looking for a method/way to return '80%' 
oehaut
  • 129
  • 2
  • 9
  • You would have to use [the CSSOM](https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model) to inspect the value in the style sheet. I would suggest using math to figure out the percentages manually. – Heretic Monkey May 03 '19 at 18:34
  • There's a jQuery way of getting height in percentage, https://api.jquery.com/height/, – Aditya Thakur May 03 '19 at 18:37

2 Answers2

0

Can't you just take the height of the element and divide it by the height of its parent element times 100?

  • Thanks, this was actually much easier this way than trying to read the value directly, and that seems to work perfectly for my case. – oehaut May 03 '19 at 18:51
  • This doesn't answer the question as it was asked, though. It may solve your overall problem, but it doesn't "return ... the height define[d] in the CSS". If you're going to change the question mid-stream, be sure to update it accordingly so the question and accepted answer match. – isherwood May 03 '19 at 20:34
0
var PctHeight = Math.round(container.clientHeight / body.clientHeight * 100.0);

Assuming most people aren't going to set fractional % values, taking the element's height divided by the containing element's height should get you the value you want.

Ryan Grange
  • 111
  • 5
  • While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – nircraft May 03 '19 at 19:26