I have following code
It's null
because you're calling the script before the DOM has been loaded.
Wrap your script in a function which will be invoked onload
, e.g.:
window.onload = function() {
var q = new foo();
q.run('yellow');
};
This JS code will run before the DOM is ready so the node will not be found. To perform execution only once the DOM is ready, you could use the window.onload event handler.
By the time the script is parsed, only the <html>
and <head>
tags have been loaded. There are several ways you can fix this:
<script>
tags at the end of your document, instead of at the beginning<script type="text/javascript" src="OtherFile.js"></script>
window.onload = function () { yourCodeHere(); }
, which will halt execution of your code until the window has loaded.