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>
function myFunction() {
  document.getElementById("example").innerHTML = "Text changed.";

<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>



JavaScript in the Head Section

Click on the button to change the text.

Hope you find it helpful.

Enjoy coding!

Read also:

JavaScript Introduction