DEV Community

Cover image for How to write JavaScript code inside the HTML itself?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to write JavaScript code inside the HTML itself?

Originally posted here!

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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 😃.


Discussion (0)