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

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.

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.

Comments

Your Answer

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.