user3761308
user3761308

Reputation: 791

Incorrect height of div returned by JS

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.

Upvotes: 8

Views: 11167

Answers (3)

Ashiquzzaman
Ashiquzzaman

Reputation: 5284

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;

Upvotes: 7

Ananya
Ananya

Reputation: 211

What I can see, here I'm getting perfect height. Can you please give your code that you have tried so far?

<!DOCTYPE html>
<html>
<head>
	<title></title>

</head>
<body>
	<div id="foo">HELLO WORLD!!!</div>
	<script type="text/javascript">


	var div= document.getElementById('foo');
	console.log(div);
	console.log(div.scrollHeight);
	console.log(div.clientHeight);
	console.log(div.offsetHeight);
	</script>
</body>
</html>

Upvotes: 1

Neel
Neel

Reputation: 155

Use .load to wait till that element is loaded in the dom

$('#foo').load(function(){
  // your code to find height
  $('#foo').height()
  });

Upvotes: 0

Related Questions