Hello World Master

Tutorials, articles and quizzes on Software Development

Javascript > Articles

How to add Javascript to a webpage

To add Javascript to a webpage we need a HTML page to work with

Creating a file with the js extension

To add Javascript to our webpage, let’s go into the folder where our HTML file is located in and add a new file using our code editor. I will be using Visual Studio Code but the steps to create a new file should be the similar if not the same with other text editors.

To create a new file click on File >> New File.

Immediately we want to save it as a file with a .js extension so after you created the new Untitled file go back to the menu and click File >> Save As and save the file with the name “script.js”.

<<Todo add image here>>

Using a JS file in an HTML file

To use our newly created CSS file in an HTML file, we need to:

  1. Open up our index.html file
  2. Add a script tag inside the head tag
  3. Have the script tag point to our script.js file

After opening up our HTML file, let’s add a script tag. For our script tag, we don’t need both an opening and closing tag. We’re just going to be defining attributes in our tag.

Here is what our script tag will look like

<script src="./script.js" async/>
  • src specifics the path of the script we’re pointing to. In this case, our resource is in the root of our webpage folder in a file named “script.js”
  • async lets our page load while we wait for our script to load
<!DOCTYPE html>
    <title>Your first webpage</title>
    <script src="./script.js" async/>  

    <h1> This is my first webpage </h1>

Using a Javascript file to change the text in an HTML page

In your code editor, go back to your script.js file and add the following code to your blank file.

document.getElementsByTagName('h1')[0].innerText = "This is my first webpage now with Javascript!"

This Javascript code gets the first tag

When you open back up your page by opening index.html with Chrome or another web browser, you should see the text “This is my first webpage now with Javascript!” instead