Categories
Web development

How to add JavaScript to HTML?

JavaScript is the programming language for the web and can update and change both HTML and CSS.

How to add JavaScript to HTML?

You can place any number of scripts in your HTML document.

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, in the <body> section, or after the </body> close tag, depending on when you want Java Script to load. 


In this example, a JavaScript function is placed in <head> section of HTML page. The function is invoked (called) when a button is clicked: 

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
  document.getElementById("example").innerHTML = "Text changed.";
}
</script>
</head>
<body>

<h4>JavaScript in the Head Section</h4>

<p id="example">Click on the button to change the text.</p>

<button type="button" onclick="myFunction()">Try it</button>

</body>
</html> 

Output:

JavaScript in the Head Section

Click on the button to change the text.


Hope you find it helpful.

Enjoy coding!

Read also:

JavaScript Introduction

HTML DOM