I have following code
<html>
<head>
<script language="JavaScript">
function foo(q) {
this.run=function(color){
var x=document.getElementById("ff");
alert(x); // <----x=null
};
}
var q=new foo();
q.run("yellow");
</script>
</head>
<body>
<div id="ff"></div>
</body>
</html>
does anyone has idea why x=null
This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
That means that any call to a DOM element which occurs before that DOM element appears in the HTML, will fail. The div appears after the script . At the moment the script is executed, the element does not exist yet and getElementById will return null .
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');
};
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With