Free beginner tutorial

JavaScript DOM and Click Events

The Document Object Model (DOM) represents a web page as objects that JavaScript can read and update. Events let your code respond to actions such as clicks.

HTML for the example

Start with these elements. The live region announces the updated message to assistive technology:

<h1 id="page-title">Welcome</h1>
<button type="button" id="hello-button">Say hello</button>
<p id="message" aria-live="polite"></p>

Select an element

Use document.querySelector() to find the first element that matches a CSS selector.

const title = document.querySelector("#page-title");
title.textContent = "Welcome!";

Use textContent for plain text. Avoid assigning untrusted input to innerHTML, because it can interpret that input as markup.

Respond to a button click

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

button.addEventListener("click", () => {
  const message = document.querySelector("#message");
  message.textContent = "You clicked the button.";
});

The script needs the hello-button and message elements shown above. Add the script with defer or place it after the HTML so the elements exist when the script runs.

Check for missing elements

If a selector does not match anything, it returns null. When the markup may vary, check the result before trying to update it.

const notice = document.querySelector(".notice");

if (notice) {
  notice.textContent = "Saved";
}