How to write JavaScript code inside the HTML itself?

August 20, 2021 - 2 min read

To write JavaScript code inside the HTML template itself, we can use the script tag inside the HTML template and write the JavaScript code inside the script tag block.

TL;DR

<!DOCTYPE html>
<html lang="en">
  <script>
    // Your JavScript code can written inside this script tag
    console.log("Hello World from JavaScript");
  </script>
  <body>
    Hello World from HTML
  </body>
</html>

For example, let's write a basic small HTML template which shows the Hello World like this,

<!DOCTYPE html>
<html lang="en">
  <body>
    Hello World from HTML
  </body>
</html>

Now to write the JavaScript code in the HTML template first we have to write a script tag. It can be done like this,

<!DOCTYPE html>
<html lang="en">
  <script>
    // Your JavScript code can written inside this script tag
    console.log("Hello World from JavaScript");
  </script>
  <body>
    Hello World from HTML
  </body>
</html>

As you can see we have defined a script tag in the <script></script> format above the body tag.

  • **You don't have to write the script tag before the body tag. You can insert the script tag anywhere in the HTML template and it will work. **

Now if you look in the browser console we can see the Hello World from JavaScript output which shows us that the JavaScript code has been executed successfully.

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.