Skip to content
Parwaz DigitalMarketing · Web · Courses

Web Development Course · Module 3, lesson 4

The DOM: changing pages and handling events

Use JavaScript to select elements, update content and classes, and respond to clicks and form input through the Document Object Model.

What you will learn

  • Select elements with querySelector and querySelectorAll
  • Change text, attributes and classes on the page
  • Respond to user actions with addEventListener

When a browser loads HTML, it builds the Document Object Model, or DOM, a tree of objects representing every element. JavaScript can read and change this tree. document.querySelector(".menu-button") returns the first element matching a CSS selector, and querySelectorAll returns all matches. Once you have an element, you can change its textContent, its attributes, or its classes through classList.

Events connect your code to what people do. button.addEventListener("click", () => { ... }) runs a function each time the button is clicked. Other common events include input on text fields, submit on forms and keydown on the keyboard. For a form, call event.preventDefault() inside the submit handler if you want to handle the data with JavaScript instead of reloading the page.

A clean pattern is to keep styling in CSS and use JavaScript only to toggle classes. For the mobile menu from the last module, a click handler can run menu.classList.toggle("hidden") and update the button's aria-expanded attribute to true or false. To add content, create elements with document.createElement and append them. Use textContent rather than innerHTML for user-supplied text to avoid injecting unsafe code.

Practice task

Make your bakery navigation menu button show and hide the links on mobile with a click handler, updating aria-expanded each time. Then render your product array from the last lesson as list items.

Web Development Course

Learn this properly,with a final project.

These pages summarise each lesson. The full course teaches them hands-on. Message us for the current fee, schedule, and format.

Available for new projects — Replies within one business day