1

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...

asked Mar 3, 2014 at 2:59
1
  • Check the value of con, it will be null, which means it has been assigned a value and is available. Commented Mar 3, 2014 at 3:09

2 Answers 2

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.

answered Mar 3, 2014 at 3:01
Sign up to request clarification or add additional context in comments.

Comments

0

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.

answered Mar 3, 2014 at 3:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.