3 Way to Add Javascript Code in HTML

Share This Post

On this page, you will learn how to add Javascript Code in HTML links in HTML. So you have just started with Javascript and wondering how to properly add a javascript link into an HTML file? Well, there are a few ways to include Javascript into HTML, and here is a quick answer:

Add Javascript Code in HTML

(“1.”) you can use the tag in HTML. And

Define a pair of tags in the HTML and we write the javascript code between them.

You can write long JavaScript codes in separate files, as dividing the code into portions makes it more readable.

It is suggested to only implement short JavaScript codes inside the tag. Otherwise, the code can become hard to read.

First, we’ll show you how you can add javascript in HTML using the tag: The example below shows a JavaScript myFunction().

<!DOCTYPE html>
<html>
<head>
    <script> 
      function myFunction() { 
         document.getElementById("click").innerHTML = "thewholeblog.com!"; 
      } 
   </script> 
</head>
<body>
   <h1>A Web Page</h1>
   <p id="click">thewholeblog.com?</p>
   <button type="button" onclick="myFunction()">Answer!</button>
</body> 
</html>      

The second way you can use in the tag: Our next example defines how JavaScript myFunction() function, which is called upon a button click, is placed in the section.

<!DOCTYPE html>
<html>
<body>
   <h1>Thewholeblog.com</h1>
   <p id="click">thewholeblog.com?</p>
   <button type="button" onclick="myFunction()">Answer!</button>
   <script> 
      function myFunction() { 
         document.getElementById("click").innerHTML = "I love learning JavaScript!"; 
      } 
   </script>  
</body>
</html>

External JavaScript:

The three and last way is the link of the script tag. You should only use inline JavaScript when your code is just a few lines. In other cases, you should place your JavaScript code in a separate file and link it to your HTML file.

The external script will behave the same way as it would when written in a <script> tag. Let’s take a look.

function myFunction() {     
   document.getElementById("example").innerHTML = "I love JavaScript!";  
}

spot_img

Related Posts

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img