Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 5

DOM Manipulation and Event Handling

Recommended resources

Welcome to our next lesson. In the previous session, we sharpened your understanding of JavaScript's variable declarations—var, let, and const—focusing on the critical concepts of scope and hoisting. Now that you have a firm grasp on how to manage data within your scripts, we'll shift our focus to how JavaScript interacts with the web page itself.

This lesson addresses a cornerstone of client-side scripting: Document Object Model (DOM) manipulation and event handling. You will learn the correct methods to find, create, and modify HTML elements using JavaScript. We'll then explore modern patterns for handling user interactions like clicks and mouse movements. For your exam preparation, we will emphasize the precise syntax and best practices that are often the subject of QCM questions.

The DOM: Your Script's Gateway to the Page

The browser creates a Document Object Model (DOM) from an HTML document, representing it as a tree of objects. Each object, or node, in this tree corresponds to a part of the document, such as an element, an attribute, or a piece of text. JavaScript can access and modify this tree, allowing you to dynamically change the content and structure of your web page.


Finding and Modifying DOM Elements

Your first task in DOM manipulation is always to select the element(s) you want to work with. While older methods like getElementById() exist, modern JavaScript largely relies on querySelector() and querySelectorAll(), which use CSS selector syntax.

  • querySelector(): Returns the first element that matches the specified selector.
  • querySelectorAll(): Returns a NodeList containing all elements that match the selector.

A key distinction for exams is the difference between a NodeList (returned by querySelectorAll) and an HTMLCollection (returned by older methods like getElementsByTagName).

This cheat sheet summarizes the key differences between Node/Element and NodeList/HTMLCollection, and illustrates common DOM traversal properties.

As the cheat sheet highlights, a NodeList can contain any node type (elements, text, comments) and has methods like forEach. An HTMLCollection only contains elements and is typically "live," meaning it automatically updates if elements are added or removed from the DOM. NodeLists returned by querySelectorAll are static. This "live" vs. "static" behavior is a classic QCM topic.

Once you've selected an element, you can modify its content, attributes, and style. The video below provides an excellent, fast-paced review of the most common manipulation techniques.

Learn DOM Manipulation In 18 Minutes

This "Web Dev Simplified" video is a concise, practical guide to the most essential DOM manipulation methods. It's perfect for quickly refreshing your existing knowledge.

Please watch the following segments: Adding Elements: This section introduces document.createElement() and the modern append() method. Note the key difference he explains between append() and the older appendChild(). Modifying Content: Here, the video compares innerText, textContent, and the powerful but potentially insecure innerHTML. Pay close attention to the security warning about innerHTML, as this is a frequent point of discussion. Modifying Attributes: Watch the segment from this timestamp to review getAttribute, setAttribute, removeAttribute, and the very useful dataset property for working with data-* attributes. Modifying Classes: This part covers the classList API (add, remove, toggle), which is the standard way to manipulate an element's classes. Modifying Styles: Finally, watch this brief section on changing inline CSS via the style property.


Best Practices for DOM Manipulation

Writing efficient and maintainable DOM manipulation code is a hallmark of a professional developer. For your exam, demonstrating knowledge of best practices can set you apart.

JS DOM Manipulation Best Practices – with Examples

This freeCodeCamp article reinforces the methods from the video and introduces several important patterns for performance and security.

Please read the following sections: Cache Selected Elements: This explains the performance benefit of storing a frequently accessed element in a variable rather than querying the DOM repeatedly. Use CSS Classes: This reinforces the best practice of using classList to toggle predefined CSS classes instead of manipulating inline styles directly. Use innerHTML with Caution: This section provides another perspective on the security risks of innerHTML and when to prefer textContent. Batch DOM Updates: This introduces DocumentFragment, a powerful performance pattern for making multiple DOM changes in memory before performing a single "reflow" on the actual page.


Making Pages Interactive: Event Handling

Event handling is how you make your web pages respond to user actions. An event is a signal that something has happened, such as a mouse click, a key press, or the page finishing loading. You use event listeners to "listen" for these events and run a specific function (a handler or callback) when they occur.

There are a few ways to attach event handlers, but the modern standard is element.addEventListener().

Event Handling Patterns in JavaScript | Learn Code With Durgesh - Learn Code with Durgesh

This article from "Learn Code With Durgesh" gives a quick and clear overview of the historical and modern ways to handle events.

Quickly review the first three patterns described: Inline Event Handling: The old onclick="" attribute in HTML. DOM Property Event Handling: Assigning a function to a property like element.onclick. Note that this only allows one handler per event. addEventListener(): The modern, flexible, and preferred method that allows for multiple handlers.


Event Propagation: Bubbling and Capturing

A crucial concept for any exam is event propagation. When an event occurs on an element, it doesn't just fire on that single element. The event travels through the DOM in two phases:

  1. Capture Phase: The event travels down from the window object to the target element's parent.
  2. Target Phase: The event reaches the target element.
  3. Bubble Phase: The event travels up from the target element back to the window object.
This diagram clearly illustrates the path of an event. By default, most event listeners react during the Bubble phase.

You can control which phase your listener responds to. This behavior, along with how to stop it, is a complex but important topic.


Event Delegation and Listener Management

The concept of event propagation enables a powerful performance pattern called event delegation. Instead of adding dozens of event listeners to child elements, you can add a single listener to a parent container. When an event bubbles up from a child, the parent's listener can catch it and determine which child it came from using the event.target property. This is especially useful for handling events on dynamically generated content.

The following video masterfully explains propagation, delegation, and how to properly add and remove listeners.

Learn JavaScript Event Listeners In 18 Minutes

This second video from "Web Dev Simplified" is an essential guide to the nuances of event listeners. It covers concepts that frequently appear in technical interviews and exams.

Please watch these key segments carefully: The Basics & The Event Object: Start from the beginning to see how addEventListener is used and how the event object, particularly e.target, provides context. Propagation: Capture vs. Bubble: The segment from this timestamp is critical. It provides an in-depth explanation of the capture and bubble phases and shows how to use the third argument of addEventListener to listen on the capture phase. Stopping Propagation: Watch this part to learn about e.stopPropagation() and how it prevents an event from continuing its journey through the DOM tree. Removing Listeners: This section explains the { once: true } option and demonstrates why you must use a named function (not an anonymous one) to successfully use removeEventListener(). This is a classic exam gotcha. Event Delegation: The final segment from this timestamp provides a brilliant, practical example of event delegation and why it's superior for handling events on dynamically added elements.


Conclusion

In this lesson, we've reviewed the essential methods and patterns for interacting with a web page using JavaScript. With your professional background, these concepts are likely familiar, but mastering the specific terminology (NodeList vs. HTMLCollection), security considerations (innerHTML), and advanced patterns (propagation, delegation, DocumentFragment) is what will give you an edge in the QCM exam.

Key Takeaways:

  • Selection: Use querySelector and querySelectorAll for their power and consistency.
  • Modification: Prefer textContent for security and classList for maintainability. Use DocumentFragment to batch multiple updates for better performance.
  • Event Handling: Always use addEventListener for its flexibility.
  • Event Propagation: Understand that events travel down (capture) and then up (bubble) the DOM tree.
  • Event Delegation: Leverage event bubbling to efficiently manage events on multiple or dynamic elements by placing a single listener on a common ancestor.

In our next lesson, we will focus on a skill that is directly tested in many QCM formats: tracing the output of JavaScript code snippets involving loops, conditionals, and functions. The DOM manipulation and event handling skills you've just reviewed will provide a practical context for the code you'll be analyzing.