Javascript Where To


Before you write any Javascript code, you need to know where to place/insert or write your Javascript code.

On the web, Javascript codes live inside HTML files.

There are 3 ways to insert your Javascript code in HTML.

  • Inside <script> tags in the HTML’s <head> section
  • Inside <script> tags in the HTML’s <body> section
  • External Javascript file example.js ( .js is the file extension for Javascript files )

The <script> tag

In HTML, Javascript code is inserted inside <script> and </script> tags.

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

Try it on CodePen

Note: Old versions of JavaScript may use type attribute:
<script type=”text/javascript”>
But it’s no longer required. Because JavaScript is the default scripting language in HTML5.


JavaScript in <head> or <body>

You can write your JavaScript codes in both HTML <head> or <body> section or both. Let’s see them one by one.


JavaScript in <head>

In this example, we have a JavaScript function inside HTML’s <head> section.

the function is called or invoked when you click the button.
Try it to see what it does.

<!DOCTYPE html>
<html>

<head>
<script>
function doSomething() {
  document.getElementById("demo").innerHTML = "Hello World!";
}
</script>
</head>
<body>
<h1>My website</h1>
<p id="demo">My first post</p>
<button type="button" onclick="doSomething()">Try it</button>

</body>

Try it on CodePen


JavaScript in <body>

In this example, we just changed the paragraph text by picking its HTML ID.

<!DOCTYPE html>
<html>

<head>
</head>
<body>
  
<h1>My website</h1>
<p id="demo">My first post</p>
  <script>

  document.getElementById("demo").innerHTML = "Hello World!";

</script>
</body>

Try it on CodePen

About the author

Leave a Reply

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