How to get the height in pixels in pure javascript?
Asked Answered
M

1

8

I have got a forum with the following HTML structure:

<div id="header">Contents</div>
<div id="main">Contents</div>
<div id="footer">Contents</div>

Basically, I need to set the height of #main to the height of the document minus the height of the other 2 elements. The problem is I have to do it without jquery. I googled the problem and found the clientHeight method, but it returns the height as a number, while I need it as pixels.

So, the question is:

Is there any way to get the height in pixels in pure javascript?

Microtome answered 28/7, 2017 at 12:23 Comment(5)
Why not use CSS?Mishamishaan
Those numbers are in pixels right?Electrostatic
You just have to round it via Math.round and add the string 'px'. But I agree to @evolutionxbox, a CSS solution would be cleaner.Hallowed
The #header and #footer don't have fixed height, otherwise I'd have used CSS. I'll try Stephan's solution and come back with a response.Microtome
Don't use JavaScript for thisAlfreda
G
8

The property .clientHeight will return a number (the height in pixels).

In your case, below is the code to reset the height of div#main. Note that we're adding a "px" at the end for .style.height to work:

document.getElementById('main').style.height = parseInt(window.innerHeight) -
document.getElementById('header').clientHeight + 
document.getElementById('footer').clientHeight + "px";
<div id="header">CONTENT</div>
<div id="main">CONTENT</div>
<div id="footer">CONTENT</div>
Goosestep answered 28/7, 2017 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.