Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jQuery return null for the height of the div?

Tags:

jquery

height

$(document).ready(function(){

  function getDocumentHeight()
  {
     // What's the page height?
     var height = $('#mainbody').height();
     alert(height);
   ...
 getDocumentHeight();  }

jQuery keeps alerting null for the height of my #mainbody div. I don't get why, it should at least be 500px or so.

like image 787
matt Avatar asked Sep 09 '10 21:09

matt


People also ask

How do you find the height of a div?

Method 1: Using the offsetHeight property: The offsetHeight property of an element is a read-only property and used to return the height of an element in pixels. It includes any borders or padding of the element. This property can be used to find the height of the <div> element.

What is jQuery height?

In jQuery, height method is used to get the height of any element in HTML. The height method sets and returns the height of the HTML elements. Method 1: The height() method returns the first matched element's height, But the height(value) method sets all matched elements height.

What is outerHeight in jQuery?

The outerHeight() method in jQuery is used to find the outer height of the specified element. Outer height of an element includes padding and border. Syntax: $(selector).outerHeight(includeMargin)


1 Answers

If the content is being loaded dynmically, the elements may not have a height yet. Try moving this code to the bottom of the page, directly above and see if that resolves.

UPDATE: Try placing your code in

$(window).load(function() {
  var height = $('#mainbody').height();
  alert(height);
});

outside of your

$(document).ready();
like image 55
Steven Avatar answered Oct 11 '22 19:10

Steven