How To Insert JavaScript in HTML?


There are two ways to Insert/Connect JavaScript to HTML documents. They are:


Use External JavaScript

You can create external JavaScript and link it to the HTML document. First of all, create a JavaScript file, for example, MyScript.js, and type all the JavaScript code you want. Then goto HTML document and inside <head> section add this code.

<script src="MyScript.js"></script>

Syntax:

<script src="filename.js"></script>


Use JavaScript inside the HTML document

You can also type JavaScript code inside the HTML document using <script></script> tag inside <head> or <body> section. For example:
<html>
<head>
</head>
<body>
 <button onclick="text()">Click</button>
  <button onclick="date()">Date</button>
  <p id="demo"></p>
  <p id="date"></p>
 
  <script>
      function text(){
  document.getElementById('demo').innerHTML="IronMan";
      }
      function date(){
         document.getElementById('date').innerHTML=Date();
      }
  </script>
</body>
</html>


Syntax:

<script>
....JS code....
    ..............................
......................
</script>


Trending Posts

What Are The Use of Function Keys F1 to F12 on The Keyboard?

12MP vs 48MP vs 64MP vs 108MP | Does More Megapixel Equal Better Image Quality?

Can I Code If I'm Bad at Math? (Spoiler: Yes, You Can!)

🚀 Build a QR Code Generator Using HTML, CSS & JavaScript

Can A Computer Virus Affect Hardware?

AI is Learning to Code — Should Web Developers Be Worried?

The Secret to Flawless Web Design: Mastering Responsive Layouts

Can a Computer Run Without RAM?

Build a Simple Calculator Using HTML, CSS, and JavaScript 💻

How To Create A Parallelogram Using HTML and CSS?