top of page
Writer's pictureThe Tech Platform

How to Add JavaScript to HTML?



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

  1. JS is faster

  2. Simple to use

  3. Online Support

  4. Inter-operability

  5. Modern-day Scripting Language


Disadvantages of JavaScript

  1. Client-Side Security

  2. Code Visibility

  3. Time consuming

  4. Advanced Competitor

  5. Disabling JavaScript can hinder a web page



The Tech Platform

0 comments

Recent Posts

See All

留言


bottom of page