Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect height of div returned by JS

Tags:

javascript

var div = document.getElementById('foo');
console.log(div);
console.log(div.scrollHeight);

When I click on the DOM of div returned by the first log in the console, its scrollHeight is x, while the second log prints out y; x != y.

like image 801
user3761308 Avatar asked Apr 13 '17 10:04

user3761308


People also ask

What is offsetHeight in javascript?

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).

What is clientHeight in javascript?

The clientHeight property returns the viewable height of an element in pixels, including padding, but not the border, scrollbar or margin. The clientHeight property is read-only.

How is clientHeight calculated?

clientHeight can be calculated as: CSS height + CSS padding - height of horizontal scrollbar (if present). When clientHeight is used on the root element (the <html> element), (or on <body> if the document is in quirks mode), the viewport's height (excluding any scrollbar) is returned.


1 Answers

To get height of a div try-

1. JavaScript:

var clientHeight = document.getElementById('divId').clientHeight;

or

var offsetHeight = document.getElementById('divId').offsetHeight;

2. jQuery:

var height= $("#divId").height();

3. vanilla JS:

var clientHeight =  document.querySelector('#divId').clientHeight;

or

var offsetHeight = document.querySelector('#divId').offsetHeight;
like image 146
Ashiquzzaman Avatar answered Nov 15 '22 11:11

Ashiquzzaman