In my new project I have to do some content without jQuery. How to write jQuery code below in pure JavaScript?
$("#content").height()
Sure thing is, that $("#content")
is in JS var content = document.getElementById('content');
, but the .height()
is for me big problem. Please help
In my new project I have to do some content without jQuery. How to write jQuery code below in pure JavaScript?
$("#content").height()
Sure thing is, that $("#content")
is in JS var content = document.getElementById('content');
, but the .height()
is for me big problem. Please help
3 Answers
Reset to default 17Equalent to $('#content').height()
would be :
document.getElementById('content').clientHeight;
or equalent to $('#content').css('height')
document.getElementById('content').style.height;
var content = document.getElementById("content");
content.clientHeight;
As stated in the comments, adeneo's solution is not correct as it will factor in unwanted padding into the height.
To get the same dimension as jQuery's .height()
provides, this is the code you'll want to use.
const s = window.getComputedStyle(el, null),
height = el.clientHeight - parseInt(s.getPropertyValue('padding-top')) - parseInt(s.getPropertyValue('padding-bottom'));
Here is a function that will help calculate all of jQuery's height getter functions. If you want to calculate the width you'll just want to change some obvious properties in the code
function getHeight(el, type) {
if (type === 'inner') // .innerWidth()
return el.clientHeight;
else if (type === 'outer') // .outerWidth()
return el.offsetHeight;
const s = window.getComputedStyle(el, null);
if (type === 'height' || !type) // .height()
return el.clientHeight - parseInt(s.getPropertyValue('padding-top')) - parseInt(s.getPropertyValue('padding-bottom'));
else if (type === 'full') // .outerWidth( includeMargins = true )
return el.offsetHeight + parseInt(s.getPropertyValue('margin-top')) + parseInt(s.getPropertyValue('margin-bottom'));
return null;
}
clientHeight
. But you might stumble acrossoffsetHeight
someday, which you might confuse. Here is the explanation for each: stackoverflow.com/a/4106585/684932 – RaphaelDDL Commented Sep 5, 2013 at 21:31