You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.
JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document. However, if your script needs to run at a certain point within a page’s layout — like when using document.write to generate content — you should put it at the point where it should be called, usually within the <body> section.
Code Example 1:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<title>Today's Date</title>
<script>let d = new Date();
alert("Today's date is " + d);
</script>
</head>
<body>
</body>
</html>
Output:
Code Example 2:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<title>Today's Date</title>
</head>
<body>
<script>let d = new Date();
document.body.innerHTML = "<h1>Today's date is " + d + "</h1>"
</script>
</body>
</html>
Output:
Advantages of JavaScript
JS is faster
Simple to use
Online Support
Inter-operability
Modern-day Scripting Language
Disadvantages of JavaScript
Client-Side Security
Code Visibility
Time consuming
Advanced Competitor
Disabling JavaScript can hinder a web page
The Tech Platform
留言