JS Placement



Where to place JavaScript code in HTML ?

  • JavaScript Code is Embedded inside HTML Script.
  • JavaScript Code can be called by using function or can be executed by triggering event.
  • Now we can place JavaScript Code anywhere inside HTML.
  • But its good practice to write JavaScript Code at appropriate position –
    1. Inside Head
    2. Inside Body
    3. Inside Single JavaScript File

JavaScript can be placed in –

  • <body> Section
  • <head> Section

Consider Example 1 : We have put JavaScript code inside <body> tag of HTML page.

<html>
<body>

<h1>My First JS Script</h1>

<pid="para1">Paragraph 1</p>

<script type="text/javascript">
document.getElementById("para1").innerHTML="This is first Paragraph";
</script>

</body>
</html>

Output:
Where to place JavaScript code in HTML ?

Consider another case , if we place JS in head section of the HTML section then –

<html>
<head>
<script type="text/javascript">
function displayDate()
{
document.getElementById("para1").innerHTML=Date();
}
</script>
</head>

<body>

<h1>My First Web Page</h1>

<pid="para1"></p>

<buttontype="button"onclick="displayDate()">Display Date</button>

</body>
</html>

Output :

My First Web Page

Display Date