Получить высоту элемента div в JavaScript
В HTML любые свойства CSS, которые вы предоставляете элементу либо с помощью таблиц стилей CSS, либо с помощью JavaScript, устанавливаются внутри объектной модели документа (DOM). С помощью этой модели DOM вы можете легко получить доступ к этим значениям позже в коде JavaScript. Есть разные способы получить значения свойств CSS внутри JavaScript. В этой статье будет рассказано, как получить свойство CSS height из нашего кода JavaScript.
Ниже представлен созданный нами HTML-документ. Внутри у нас есть тег body , содержащий только один элемент div с идентификатором container . В теге head мы предоставили некоторые базовые стили нашему элементу div, такие как ширина, высота, граница, отступы и т. Д.

Если вы запустите указанный выше HTML-документ, вы увидите такой прямоугольник в окне браузера.
Получить ширину и высоту элемента с помощью JavaScript
В этом посте мы обсудим, как получить ширину и высоту элемента с помощью чистого JavaScript.
В JavaScript есть несколько свойств для получения ширины и высоты элемента. В этом посте представлен обзор некоторых из этих свойств.
1. Использование clientWidth а также clientHeight характеристики
В JavaScript вы можете использовать clientWidth а также clientHeight свойства, чтобы вернуть высоту элемента, включая отступы, но исключая границу, поля или полосы прокрутки. По сути, они возвращают фактическое пространство, используемое отображаемым контентом.
Например, следующий код возвращает ‘520 × 120’.
The scrollWidth а также scrollHeight свойства аналогичны clientWidth а также clientHeight свойства, за исключением того, что они возвращают фактический размер содержимого, независимо от того, сколько на самом деле видно.
2. Использование offsetWidth а также offsetHeight характеристики
В качестве альтернативы, если вам нужно включить границу и полосы прокрутки, вы можете использовать offsetWidth а также offsetHeight характеристики. Они возвращают размеры видимого содержимого элемента, включая отступы, границы и полосы прокрутки. Другими словами, они возвращают общее количество места, которое занимает элемент.
HTMLElement.offsetHeight
The HTMLElement.offsetHeight read-only property returns the height of an element, including vertical padding and borders, as an integer.
Typically, offsetHeight is a measurement in pixels of the element’s CSS height, including any borders, padding, and horizontal scrollbars (if rendered). It does not include the height of pseudo-elements such as ::before or ::after . For the document body object, the measurement includes total linear content height instead of the element’s CSS height. Floated elements extending below other linear content are ignored.
If the element is hidden (for example, by setting style.display on the element or one of its ancestors to «none» ), then 0 is returned.
Note: This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect() .
Value
Examples

The example image above shows a scrollbar and an offsetHeight which fits on the window. However, non-scrollable elements may have large offsetHeight values, much larger than the visible content. These elements are typically contained within scrollable elements; consequently, these non-scrollable elements may be completely or partly invisible, depending on the scrollTop setting of the scrollable container.
Specifications
| Specification |
|---|
| CSSOM View Module # dom-htmlelement-offsetheight |
Notes
offsetHeight is a property of the DHTML object model which was first introduced by MSIE. It is sometimes referred to as an element’s physical/graphical dimensions, or an element’s border-box height.
Как получить высоту элемента js
To get the height of an element, there are five common methods in JavaScript. Lets see the differences between each and when they should be used. Only the last method gives the correct rendered height instead of the layout height.
- style.height
- jQuery( height, innerHeight, outerHeight )
- clientHeight, offsetHeight, scrollHeight
- getComputedStyle
- getBoundingClientRect().height
Rendered height is the height that the element gets finally after all the styles and transformations are applied on that element. For example, An element has height of 100px and then gets a transform:scale(0.5). Its rendered height is 50px (after the transformation) and layout height is 100px.
style.height We can use style.height on any selected element and it will return its height. Does not include the padding, border or margin. Italways return the height along with the specific unit.
Note: Only works if we explicitly set the height as inline using the style attribute in HTML.
Syntax:
Example:
Output:
It returns empty string for “div1” and it returns “100px” for “div2”
- For “div1”:

- For “div2”:

Conclusion: It returns whatever height is specified in inline style attribute only. It does not factor in any transformations, like scale. It is not reliable and should not be used as inline styles are not ideal.
jQuery(height, innerHeight, outerHeight)
height() It returns the current height of the element. It does not include the padding, border or margin. It always returns a unit-less pixel value.
Note: The height() will always return the content height, regardless of the value of CSS box-sizing property.
Syntax:

Example 2:
Output:
It returns unit-less pixel value as 100.
Output:
innerHeight() It returns the current height of the element including the top and bottom padding but not border. It always returns a unit-less pixel value.
Syntax:

Example 3:
Output:
It returns 120 which is (10(top padding) + 100(content height) + 10(bottom-padding))

outerHeight() It returns the current height of the element including the padding, border and margin optionally. It always returns a unit-less pixel value.
Syntax:

Example 4:
Output:
(1(top border)+ 10(top padding)+ 100(content height)+1 0(bottom-padding)+ 1(bottom border)

Note: The value reported by height(), innerHeight() and outerHeight() is not guaranteed to be accurate when the element or its parent is hidden. To get accurate results, ensure the element is visible before using these methods. jQuery will attempt to temporarily show and then re-hide an element in order to measure its dimensions, but this is unreliable and (even when accurate) can significantly impact page performance. This show-and-rehide measurement feature may be removed in a future version of jQuery.
Conclusion:
All these return only the layout height, not the rendered height.
clientHeight, offsetHeight, scrollHeight
clientHeight() It returns the height of the displayed content from the element (including vertical padding but not border or margin or scrollbar). It always returns an integer value in pixels. If element is hidden, then 0 is returned. If its a scrollable element, then it will only give the height of the visible part.
Syntax:

Example 5:
Output:
It returns 120 which is (10(top padding) + 100(content height) + 10(bottom-padding))

Conclusion: If we want to find the height of the actual displayed content use clientHeight. It returns the layout height of the currently visible part of the element which is rounded to an integer value even if the result is a fraction.
offsetHeight() It returns the height that the element occupies including the vertical padding, border and scrollbars (if any). It does not include the margin. It always returns an integer value in pixels. If element is hidden, then 0 is returned.
Note: It does not include the height of pseudo elements such as ::after or ::before
Syntax:

Example 6:
Output:
It returns 122 which is (1(border-top) + 10(padding-top )+ 100(contentHeight) + 10(padding-bottom) + 1(border-bottom))

Conclusion: If you need to know the total height of an element occupies including the width of the visible content, scrollbars (if any), padding, and border, we can use offsetWidth. It returns the layout height of the currently visible part of the element which is rounded to an integer value.
scrollHeight() It returns the height of the entire content of an element, even if only part of it is visible due to scrollbars. It always returns an integer value in pixels. If the element is hidden, then 0 is returned.
Its similar to clientHeight as it includes the element and its padding, but not its border, margin or horizontal scrollbar (if present). It can also include the height of pseudo-elements such as ::before or ::after. If the element’s content can fit without a need for vertical scrollbar, its scrollHeight is equal to clientHeight.
Syntax:

Example 7:
Output:
(1(border-top) + 10(padding-top) + entireContent(visible and not visible) + 10(padding-bottom)+ 1(border-bottom))

Conclusion: If you need to know the actual size of the content, regardless of how much of it is currently visible, use scrollHeight. It includes the elements padding but not margin, border or scrollbar (if present). It returns rounded integer if the height is in fraction.
getComputedStyle() Method: The getComputedStyle() method basically allows us to retrieve the resolved CSS values of different properties. It returns a CSSStyleDeclaration object. The computed style is used in displaying the element, after “stylings” from multiple sources have been applied.
getComputedStyle().height It will return the layout height specified not the rendered height. It returns fractional pixel value. It is a resolved value, so if we use 100%, it will return the equivalent resolved value in pixel. It only gives the content height. If we want, we can access each CSS property like margin-top, margin-bottom, padding-top, padding-bottom, border-top, border-bottom individually and add them as required.