Inside which HTML element to be put the javascript?

Inside which HTML element to be put the javascript
Table of Contents

Want to know inside which HTML element to be put the Javascript? you are complete beginner and you don’t know inside which HTML element to put the Javascript code then today I will tell you where to put your Javascript in HTML.

Want to write your first Javascript hello world program then you can read this tutorial on writing your first hello world program in Javascript.

There are basically 2 ways of adding javascript to your HTML web page is by using:

  • Internal Javascript
  • External Javascript

You can use any of the way to add Javascript to HTML elements I will show you both ways so follow up with me till the end.

1. Adding Javascript to HTML using internal Javascript

The first way to add javascript to your HTML element is adding it internally into the HTML code by using the

				
					<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Internal javascript</title>
  </head>
  <body>
	<script>
	    //ADD YOUR JAVASCRIPT CODE HERE
	</script>
  </body>
</html>
				
			

As you can see above we have added the script tag inside the body tag. You can add any Javascript code inside this script tag. 

2. Adding Javascript to HTML using external Javascript

The second way of adding javascript to your HTML file or elements is by creating a seperate javascript file with .js extension and add the Javascript code there and link the javascript file in the HTML file you want to use you can use this tag to link javascript file.

				
					<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Internal javascript</title>
  </head>
  <body>
    <h1>Hello World</h1> 
    <script src="index.js"></script>
  </body>
</html>
				
			

You have to add this line of code inside the HTML body tag you need to add it at the bottom of the body tag so it loads after all the HTML elements are loaded. Inside src add the location of your file.

This way all the javascript code you have written in the javascript file will be added to the HTML elements this is the best and recommended way of adding Javascript to HTML elements. 

Summary

These were the 2 methods of adding Javascript to HTML elements I hope I solved your question “Inside which HTML element to be put the Javascript code” which is the tag or you can add it in external Javascript file.

Here are more guides which yo can find useful and helpful:

Want to stay updated on our latest coding tutorial guides and projects then you can join our Telegram channel here – Join Coderzway Telegram channel.

Thank you for reading, Have a nice day 🙂

Share This Post
Share on facebook
Share on twitter
Share on email
Share on whatsapp

Leave a Reply

Subscribe To Our Newsletter

Get updates and learn from the best

Latest Guides & Articles