0

In a scrip I try to get the width of an element like so:

var container = document.getElementById('content');
var cw = container.clientWidth;

But it gives me this error in the console:

Uncaught TypeError: Cannot read property 'clientWidth' of null

Executing the same statements in the console however, produces the desired value. How is that possible?

Screenshot of the console:

enter image description here

random_user_name
  • 25,694
  • 7
  • 76
  • 115
Flip
  • 6,233
  • 7
  • 46
  • 75

1 Answers1

0

This script is loading before the dom has finished loading (or in particular the div#content). ensure that this script is being inserted as the last element of the body (not in the head) or if div#content is being dynamically created, you may want to invest in jQuery's $(document).ready function

PhilVarg
  • 4,762
  • 2
  • 19
  • 37