how to run javascript in HTML

Running JavaScript in HTML:

We can run JavaScript in HTML using the HTML

script element. It is used to include JavaScript in HTML.

example:-



                                                                                                              HTML


<body>

<div id="root"></div>

<script type="text/javascript">

const rootElement = document.getElementById("root");

const element = document.createElement("h1");

element.textContent = "Hello World!";

element.classList.add("greeting");

rootElement.appendChild(element);

</script>

</body>


Here the type attribute specifies the type of the script. To include an external JavaScript file, we can use the HTML script element with the attribute src. The src attribute specifies the path of an external JS file.

example: -  

                                                                                                                       HTML

<script type="text/javascript" src="PATH_TO_JS_FILE.js"></script>

IMPORTANT POINTS TO NOTE:

1. When the browser comes across a script element while loading the HTML, it must wait for the script to download, execute it, and only then can it process the rest of the page.

2. So, we need to put a script element at the bottom of the page. Then the browser can see elements above it and doesn’t block the page content from showing.

3. If more than one script elements are in the HTML, the script elements will be executed in the order they appear.

Comments