Add JavaScript to HTML
There are following three ways through which we can add the JavaScript code into the HTML document:
- Include the JavaScript code in <head>…</head> tag.
- Include the JavaScript code between the <Body> …</Body> tag and after the closing of the body tag.
- 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
Output:
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
Output:
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
Output:
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.
Output: