最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to write $("#content").height() in pure JavaScript? - Stack Overflow

programmeradmin1浏览0评论

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

Share Improve this question asked Sep 5, 2013 at 21:28 user2737935user2737935 751 silver badge5 bronze badges 2
  • 1 Just as additional info: The answer is clientHeight. But you might stumble across offsetHeight someday, which you might confuse. Here is the explanation for each: stackoverflow.com/a/4106585/684932 – RaphaelDDL Commented Sep 5, 2013 at 21:31
  • stackoverflow.com/a/526352/438992 – Dave Newton Commented Sep 5, 2013 at 21:32
Add a comment  | 

3 Answers 3

Reset to default 17

Equalent 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;
}
发布评论

评论列表(0)

  1. 暂无评论