JavaScript Where To

Back to JS page

Table of Contents

The script Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.

<!DOCTYPE html>
<html>
<body>

<h2>Demo JavaScript in Body</h2>

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

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

</body>
</html>

Example 1

Result View Example

JavaScript in Head or Body

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>

<h2>Demo JavaScript in Head</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

</body>
</html>

Example 2

Result View Example

JavaScript in Body

In this example, a JavaScript function is placed in the <body> section of an HTML page.

The function is invoked when a button is clicked.

<!DOCTYPE html>
<html>
<body>

<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

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

</body>
</html>

Example 3

Result View Example

External JavaScript

Scripts can also be placed in external files.

External scripts are useful when the same code is used in many different web pages.

<!DOCTYPE html>
<html>
<body>

<h2>Demo External JavaScript</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

<script src="myScript.js"></script>

</body>
</html>

Example 4

Result View Example

Document

Document in project

You can Download PDF file.

Reference