The HTML script element allows us to write JavaScript between opening <script>tag and closing </script> tag.
You can put JavaScript in the head or body section also you can write an external JS file and link it to the HTML document.
The <script> Tag:
In HTML, JS code must be embedded between <script> and </script> tags. The <script> tag is used to identify a block of script code in the HTML page. It also loads a script file with the src attribute.
Syntax:
<script>
//write JavaScript code here..
</script>
Let see where and how we can write JS code.
JavaScript in <head> or <body>:
There is a flexibility to include JS code anywhere in an HTML document. You can add any number of scripts in an HTML document and these scripts can be put in <head>or in the <body> section of an HTML page.
JavaScript in <head>:
In the following example, a JS function is placed in the <head> section of an HTML page and this function is called when a button is clicked.
Example:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "JavaScript is a client-side scripting language and it is used to enhance the interaction of the user with the webpage.";
}
</script>
</head>
<body>
<p id="demo"> JavaScript </p>
<button type="button" onclick="myFunction()"> Click on it </button>
In the following example, a JS function is placed in the <body> section of an HTML page and this function is called when a button is clicked.
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"> JavaScript </p>
<button type="button" onclick="myFunction()"> Click on it </button>/span>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "JavaScript is a client-side scripting language and it is used to enhance the interaction of the user with the webpage.";
You can write JS code in an external file with .js extension and linked it to the HTML document. The benefit of the external JS is that you can link it to multiple HTML documents and when you make changes in the main JS file it will affect all linked documents so you don’t need to make changes in every JS file.
If you want to use an external script then put the name of the script file in the src attribute of the
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok