JavaScript code can be placed inside <script> and </script> tags. The script tags can go anywhere in <body> or <head> section of HTML page.
JavaScript code must be inside <script></script> tags to translate. Anything outside of <script> tag is
taken as normal HTML code and not execute as a JavaScript code.
<html>
<body>
<p id="div_id">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("div_id").innerHTML = "Content changed.";
}
</script>
<h1>My Web Page</h1>
</body>
</html>
You can place unlimited number of scripts in an HTML page. Scripts code can be placed anywhere between <head> tag or <body> tag or both.
In below example, JavaScript code is written within <head> section of page. The function is called when a someone click on the button
<html>
<head>
<script>
function myFunction() {
document.getElementById("div_id").innerHTML = "Content changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="div_id">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
In below example, JavaScript code is written within <body> section of page. The function is called when a someone click on the button
<!DOCTYPE html>
<html>
<body>
<p id="demo">Welcome to Javascript</p>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript code";
</script>
</body>
</html>