/    Sign up×
Community /Pin to ProfileBookmark

JavaScript inside the head tag

Can you explain why the javaScript doesn’t work if JavaScript codes are placed inside <head></head> tag. Why they only work if the codes are placed in body tag?

Thank you.

<!doctype html>
<html>
<head>
<meta charset=”utf-8″>
<title>Untitled Document</title>

</head>

<body>
<p>This example calls a function which returns the value of PI:</p>

<p id=”demo”></p>

<script>
function myFunction (){
return Math.PI;
}

document.getElementById(“demo”).innerHTML = myFunction();
</script>
</body>
</html>

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@rootFeb 25.2016 — Firstly, please remember that the forum has tags to wrap code in, it makes it easier to read.

Secondly, because you are trying to access an element that has not rendered and it will only complete rendering when the whole document has loaded.

You need to delay any script until the document has loaded.

So
[code=html]<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>

<script>
function myFunction (){
return Math.PI;
}

window.onload = function(){
document.getElementById("demo").innerHTML = myFunction();
}
</script>


</head>

<body>
<p>This example calls a function which returns the value of PI:</p>

<p id="demo"></p>

</body>
</html>[/code]


The proper way (not the sloppy way) to do it is not as others will tell you, place your function in the body or at the end, thats not how you write code, another way and one that I use often is to use the JSON method of creating a function that tests for when the document has become avaiable and thne the script triggers or you can add an event listener to trigger when the document body is available.
Copy linkTweet thisAlerts:
@web90authorFeb 25.2016 — Thanks a million, sir.
×

Success!

Help @web90 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...