JavaScript Basics: Make Web Pages Come Alive · Lesson 7 of 8

Lesson 7: JavaScript in the Browser: The DOM and Events

Change a web page from JavaScript: find elements, change text and styles, and react to button clicks.

Lesson 7: JavaScript in the Browser: The DOM and Events

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.
  • textContent changes the text, and style.color changes 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

  1. Make a button that changes the page background colour.
  2. Make a counter: each click adds 1 to a number shown on the page.
  3. Make a text box and button that adds what you typed to a list.

Next lesson: a mini project.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 7: JavaScript in the Browser: The DOM and Events | MeroSir