The code is as follows :
<html>
<head>
<title>JS Test</title>
<script>
var con=document.getElementById("con");
function btn()
{
con.innerHTML="Hello";
}
</script>
</head>
<body>
<input type="button" value="Click me" onclick="btn()" />
<div id="con"></div>
</body>
</html>
I'm not getting the required result. Any one please explain why ? But I'm getting the result when con is initialized inside the function ie.
function btn()
{
con=document.getElementById("con");
con.innerHTML="Hello";
}
How to access the global variable declare outside the function? Also tried window.con , but not works.. please explain the reason...
-
Check the value of con, it will be null, which means it has been assigned a value and is available.RobG– RobG2014年03月03日 03:09:20 +00:00Commented Mar 3, 2014 at 3:09
2 Answers 2
You're running the script in the head so the DOM element doesn't exist yet. Try moving your script to the footer and you should be golden.
Comments
Just put the script at the bottom.
Indeed, when document.getElementById("con"); is not declared in a function, the targeted element is about to be retrieved directly but doesn't exist yet.