Javatpoint Logo
Javatpoint Logo

Add JavaScript to HTML

There are following three ways through which we can add the JavaScript code into the HTML document:

  1. Include the JavaScript code in <head>…</head> tag.
  2. Include the JavaScript code between the <Body> …</Body> tag and after the closing of the body tag.
  3. Link the separate file of JavaScript in HTML

Include the JavaScript Code in <head> tag.

In this section, you will learn to include the JavaScript code between the <head> and </head> tag.

Syntax

In the above syntax, the JavaScript code written between the <script>……. </script> tag is put between the <head> and </head> tag in HTML file.

Example

Test it Now

Output:

Add JavaScript to HTML

2. i) Include the JavaScript code in the <body> tag.

In this section, you will learn about how to include the JavaScript code in-between the <body> and </body> tag.

Syntax

In the above syntax, the JavaScript code written between the <script>……. </script> tag is put in-between of the <body> and </body> tag in HTML file.

Example

Test it Now

Output:

Add JavaScript to HTML

ii) Include the JavaScript code after the <body> tag.

In this section, you will learn to include the JavaScript code after the <body> tag.

Syntax

In the above syntax, the JavaScript code written between the <script>……. </script> tag is put after the <body>…</body> tag in HTML file.

Example

Test it Now

Output:

Add JavaScript to HTML

Link the Separate file of JavaScript in HTML

In this section, you will learn to include the file of JavaScript code in the HTML file.

Syntax

In the above syntax, the src is an attribute of <script> tag used for specifying the name of the JavaScript file.

Example

The following code is written in JavaScript (inc), which is saved by .js extension.

The following code is written in an HTML file which uses the src attribute in the <script> tag to specify the above JavaScript file.

Test it Now

Output:

Add JavaScript to HTML





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA