Where to use JavaScript?

Where to use JavaScrip? But, before that we need to understand the JavaScript tag.
We insert HTML code between <html> and </html> tag, same way we use <script> and </script> tag to write a JavaScript code.

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

Where to use JavaScript in <head> or <body>?
You can place your script anywhere in the HTML document. <body>, or in the <head> section, or in both.

Ample Designs - JavaScript Tag

JavaScript in <head>

In this example, a JavaScript function is placed in the <head> section of an HTML page.
On button clicked The function will called:

Copy the below HTML code into Notepad:

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("Test").innerHTML = "HTML Paragraph changed with JavaScript Result.";
}
</script>
</head>
<body>
<h3>JavaScript in Head</h3>

<p id="Test">Plain HTML Paragraph</p>
<button type="button" onclick="myFunction()"> Click Me </button>
</body>
</html>

Final output will show following result:

JavaScript in Head

Plain HTML Paragraph

JavaScript in <body>

In this example, a JavaScript function is placed in the <head> section of an HTML page.
On button clicked The function will called:

Copy the below HTML code into Notepad:

<!DOCTYPE html>
<html>
<body>

<h3>JavaScript in Body</h3>

<p id="Test1">Plain HTML Paragraph</p>

<button type="button" onclick="myFunction1()"> Click Me </button>

<script>
function myFunction1() {
  document.getElementById("Test1").innerHTML = "HTML Paragraph changed with JavaScript Result.";
}
</script>

</body>
</html>

Final output will show following result:

JavaScript in Body

Plain HTML Paragraph

Leave a Reply

Your email address will not be published. Required fields are marked *