Learning Labs Frontend 2026/Week 4/JavaScript in a Web Page

JavaScript in a Web Page

JavaScript in a Web Page

13. From the Console to a Web Page

The console is useful for learning and testing, but websites normally run JavaScript from an HTML page.

For example:

<!DOCTYPE html>
<html>
<head>
    <title>My Website</title>
</head>
<body>

    <h1>Hello</h1>

    <script>
        console.log("JavaScript is running!");
    </script>

</body>
</html>

The <script> element tells the browser that the content inside it is JavaScript.

You can also put JavaScript in a separate file.

index.html:

<script src="script.js"></script>

script.js:

console.log("JavaScript is running!");

Using a separate file is usually better once the program becomes larger.

14. JavaScript and the DOM

Now we move from programming in the console to controlling the actual web page.

The browser represents the HTML document as a structure called the DOM, or Document Object Model.

For example, this HTML:

<h1>Hello</h1>
<button>Click me</button>

becomes something JavaScript can access and modify.

We can select an element using:

document.querySelector("h1");

For example:

const heading = document.querySelector("h1");

heading.textContent = "Hello, JavaScript!";

JavaScript has now changed the content of the <h1>.

This is one of the key differences between running JavaScript in the console and using JavaScript to build an interactive web page.

15. Handling Clicks

JavaScript can react to user actions.

Suppose we have:

<button id="button">Click me</button>

We can select it:

const button = document.querySelector("#button");

Then listen for a click:

button.addEventListener("click", () => {
    alert("Button clicked!");
});

The basic idea is:

User clicks button
        ↓
Browser detects the click
        ↓
JavaScript event listener runs
        ↓
Your code executes

This is called event handling.