Now we connect JavaScript to a real page. The browser turns your HTML into a tree of objects called the DOM (Document Object Model). JavaScript can find any element in it and change it.
A page you can try
Save this as page.html and open it in your browser. The code in this lesson needs a browser, so it is shown but not run here.
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hello</h1>
<button id="btn">Click me</button>
<script>
const title = document.getElementById("title");
const button = document.getElementById("btn");
button.addEventListener("click", function () {
title.textContent = "You clicked the button!";
title.style.color = "crimson";
});
</script>
</body>
</html>
What happened
document.getElementById("title")finds the element with that id.addEventListener("click", ...)says: when this is clicked, run my function.textContentchanges the text, andstyle.colorchanges the colour.
Reading what the user types
<input id="name" placeholder="Your name">
<button id="go">Greet</button>
<p id="out"></p>
<script>
document.getElementById("go").addEventListener("click", () => {
const name = document.getElementById("name").value;
document.getElementById("out").textContent = `Namaste, ${name}!`;
});
</script>
An input's .value is whatever the user typed (always text). Put the <script> after the elements it uses, so they exist when the code runs.
Adding new elements
const li = document.createElement("li");
li.textContent = "A new item";
document.getElementById("list").appendChild(li);
Events are the heart of interactive pages: click, input, submit, keydown, mouseover. Learn a few and you can build almost anything small.
Try it yourself
- Make a button that changes the page background colour.
- Make a counter: each click adds 1 to a number shown on the page.
- Make a text box and button that adds what you typed to a list.
Next lesson: a mini project.

Comments
Loading comments…