DEV Community

Cover image for How to Work with the DOM: Event Listeners and Manipulation
Rowsan Ali
Rowsan Ali

Posted on

How to Work with the DOM: Event Listeners and Manipulation

The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of objects, where each object corresponds to a part of the document, such as elements, attributes, and text. JavaScript can interact with the DOM to dynamically change the content, structure, and style of a web page.

If you're a developer or just starting out.
I recommend signing up for our free newsletter 'ACE Dev' .
It gets delivered to your inbox and includes actionable steps and helpful resources.
Join us now

In this blog post, we'll explore two fundamental aspects of working with the DOM: event listeners and DOM manipulation. We'll cover how to attach event listeners to DOM elements to respond to user interactions and how to manipulate the DOM to dynamically update the content and appearance of a web page.

Table of Contents

  1. What is the DOM?
  2. Selecting DOM Elements
  3. Event Listeners
  4. DOM Manipulation
  5. Conclusion

1. What is the DOM?

The DOM is a tree-like representation of the HTML document. Each node in the tree represents an element, attribute, or piece of text. JavaScript can interact with the DOM to dynamically change the content, structure, and style of a web page.

For example, consider the following HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOM Example</title>
</head>
<body>
    <h1 id="title">Hello, World!</h1>
    <button id="changeText">Change Text</button>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this example, the DOM tree would have a root node (<html>), with child nodes for <head> and <body>. The <body> element contains an <h1> element and a <button> element.

2. Selecting DOM Elements

Before you can manipulate the DOM or attach event listeners, you need to select the DOM elements you want to work with. JavaScript provides several methods for selecting elements:

  • document.getElementById(id): Selects an element by its id attribute.
  • document.querySelector(selector): Selects the first element that matches a CSS selector.
  • document.querySelectorAll(selector): Selects all elements that match a CSS selector.

For example, to select the <h1> element with the id of title, you can use:

const titleElement = document.getElementById('title');
Enter fullscreen mode Exit fullscreen mode

Or, using querySelector:

const titleElement = document.querySelector('#title');
Enter fullscreen mode Exit fullscreen mode

3. Event Listeners

Event listeners are functions that wait for a specific event to occur on a DOM element, such as a click, mouseover, or keypress. When the event occurs, the event listener executes a callback function.

Adding Event Listeners

To add an event listener to an element, you can use the addEventListener method:

element.addEventListener(eventType, callbackFunction);
Enter fullscreen mode Exit fullscreen mode

For example, let's add an event listener to the button in our HTML that changes the text of the <h1> element when clicked:

const changeTextButton = document.getElementById('changeText');
const titleElement = document.getElementById('title');

changeTextButton.addEventListener('click', function() {
    titleElement.textContent = 'Text Changed!';
});
Enter fullscreen mode Exit fullscreen mode

In this example, when the button is clicked, the text content of the <h1> element is changed to "Text Changed!".

Common Event Types

Here are some common event types you might use:

  • click: Occurs when an element is clicked.
  • mouseover: Occurs when the mouse pointer is moved over an element.
  • mouseout: Occurs when the mouse pointer is moved out of an element.
  • keydown: Occurs when a key is pressed down.
  • keyup: Occurs when a key is released.
  • submit: Occurs when a form is submitted.

Removing Event Listeners

You can also remove an event listener using the removeEventListener method. To do this, you need to pass the same event type and callback function that was used when adding the event listener.

element.removeEventListener(eventType, callbackFunction);
Enter fullscreen mode Exit fullscreen mode

For example, let's remove the event listener we added earlier:

function changeText() {
    titleElement.textContent = 'Text Changed!';
}

changeTextButton.addEventListener('click', changeText);

// Later, to remove the event listener
changeTextButton.removeEventListener('click', changeText);
Enter fullscreen mode Exit fullscreen mode

4. DOM Manipulation

DOM manipulation involves changing the content, structure, or style of a web page dynamically using JavaScript. Let's explore some common DOM manipulation techniques.

Changing Element Content

You can change the content of an element using properties like textContent and innerHTML.

  • textContent: Sets or returns the text content of an element.
  • innerHTML: Sets or returns the HTML content of an element.

For example, to change the text content of the <h1> element:

titleElement.textContent = 'New Title';
Enter fullscreen mode Exit fullscreen mode

Or, to change the HTML content:

titleElement.innerHTML = '<em>New Title</em>';
Enter fullscreen mode Exit fullscreen mode

Modifying Element Attributes

You can modify element attributes using methods like setAttribute and getAttribute.

  • setAttribute(name, value): Sets the value of an attribute.
  • getAttribute(name): Returns the value of an attribute.

For example, to change the src attribute of an image:

const imageElement = document.querySelector('img');
imageElement.setAttribute('src', 'new-image.jpg');
Enter fullscreen mode Exit fullscreen mode

Adding and Removing Elements

You can add new elements to the DOM or remove existing ones using methods like createElement, appendChild, and removeChild.

  • createElement(tagName): Creates a new element.
  • appendChild(child): Adds a new child element to a parent element.
  • removeChild(child): Removes a child element from a parent element.

For example, let's add a new paragraph to the body:

const newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';
document.body.appendChild(newParagraph);
Enter fullscreen mode Exit fullscreen mode

To remove the paragraph:

document.body.removeChild(newParagraph);
Enter fullscreen mode Exit fullscreen mode

5. Conclusion

Working with the DOM is a fundamental skill for web developers. By understanding how to select elements, attach event listeners, and manipulate the DOM, you can create dynamic and interactive web pages.

In this blog post, we covered the basics of selecting DOM elements, adding and removing event listeners, and performing common DOM manipulation tasks. With these skills, you can start building more interactive and responsive web applications.

Remember, the DOM is a powerful tool, but it's important to use it efficiently to avoid performance issues. Always consider the impact of your DOM manipulations on the overall performance of your web page.

If you're a developer or just starting out.
I recommend signing up for our free newsletter 'ACE Dev' .
It gets delivered to your inbox and includes actionable steps and helpful resources.
Join us now

Top comments (0)