Get Started in JavaScript Episode 3: DOM and DOM Manipulation

This article covers DOM manipulation, event handling, and creating dynamic web pages in JavaScript. Learn techniques to select, modify DOM elements, add event listeners, build an interactive to-do app.

Welcome to the third installment of our comprehensive JavaScript learning series. Before diving into this article, I highly recommend reading Episode 1 and Episode 2.

In this episode, we dive into the exciting world of DOM Manipulation, a fundamental concept in web development. The Document Object Model (DOM) serves as the bridge between your JavaScript code and the structure of your web page, allowing you to create dynamic and interactive experiences for your users. By the end of this episode, you'll have a strong understanding of DOM manipulation techniques, event handling, and how to craft dynamic web pages. Let's get started!

Table of Contents

  1. Understanding the Document Object Model (DOM)
  2. Selecting and Modifying DOM Elements
  3. Event Handling
  4. Creating Dynamic Web Pages
  5. Exercise: Interactive To-Do List Application
  6. Resources for Further Learning

1. Understanding the Document Object Model (DOM)

Imagine your web page as a living, breathing entity composed of various elements: headings, paragraphs, images, and more. The DOM is like a virtual representation of this web page's structure, constructed as a tree of interconnected nodes. Each node corresponds to an HTML element, and this structure enables us to manipulate the content and appearance of our web page using JavaScript.

When your browser loads an HTML document, it creates the DOM, a data structure that enables JavaScript to access, modify, and update the content of your web page in real-time. This means that through DOM manipulation, you can change text, add or remove elements, and even alter the styling to provide a dynamic user experience.

2. Selecting and Modifying DOM Elements

To interact with the DOM, you need to first select the elements you want to work with. The DOM provides a range of methods to help you do this. One popular method is document.querySelector(), which lets you select elements using CSS-style selectors.

const header = document.querySelector('h1');
header.textContent = 'Welcome to my Website!';

You can also use document.getElementById() to select elements by their unique IDs:

const myButton = document.getElementById('myButton');
myButton.disabled = true;

After selecting an element, you can modify its properties, such as changing its text content, altering its attributes, or adjusting its styling.

3. Event Handling

Websites become truly interactive when they respond to user actions, like clicks, mouse movements, or keyboard inputs. Event handling allows you to capture and react to these actions.

For example, you can use the addEventListener() method to listen for events on specific elements:

const button = document.getElementById('myButton');
button.addEventListener('click', () => {
  alert('Button Clicked!');
});

In this example, when the button is clicked, the attached function displays an alert box. Event handling empowers you to create engaging user experiences and enables your web page to react dynamically to user interactions.

4. Creating Dynamic Web Pages

DOM manipulation is the backbone of dynamic web pages. You can add new elements, modify existing ones, or even remove elements entirely to update the content and appearance of your website in real-time.

To add a new element, you can create it using document.createElement() and then append it to an existing element using appendChild():

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

When you want to remove an element, you can use the remove() method:

const elementToRemove = document.getElementById('myElement');
elementToRemove.remove();

5. Exercise: Interactive To-Do List Application

Let's put our knowledge into practice by building an interactive to-do list application step by step.

Step 1: Setting Up the HTML Structure

Start with a basic HTML structure that includes an input field and an empty list:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>To-Do List</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>To-Do List</h1>
  <input type="text" id="taskInput" placeholder="Enter a new task">
  <ul id="taskList"></ul>
  <script src="script.js"></script>
</body>
</html>

Step 2: Styling with CSS

Style your to-do list to make it visually appealing. Create a styles.css file

5. Exercise: Interactive To-Do List Application

Let's apply our knowledge of DOM manipulation to build an interactive to-do list application. Follow these steps to create your own:

Step 1: Setting Up the HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>To-Do List</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>To-Do List</h1>
  <input type="text" id="taskInput" placeholder="Enter a new task">
  <ul id="taskList"></ul>
  <script src="script.js"></script>
</body>
</html>

Step 2: Styling with CSS

Create a styles.css file to style your to-do list.

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  text-align: center;
}

h1 {
  color: #333;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  border-bottom: 1px solid #ccc;
}

button {
  background-color: #333;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
}

Step 3: Selecting and Manipulating DOM Elements

In your script.js file, start by selecting the necessary elements and storing references to them.

const taskInput = document.getElementById('taskInput');
const taskList = document.getElementById('taskList');

Now, let's add an event listener to the input field to capture new tasks when the user presses Enter.

taskInput.addEventListener('keyup', (event) => {
  if (event.key === 'Enter' && taskInput.value.trim() !== '') {
    // Create a new task item
    const taskItem = document.createElement('li');
    taskItem.innerHTML = `
      ${taskInput.value}
      <button>Delete</button>
    `;
    
    // Add task to the list
    taskList.appendChild(taskItem);
    
    // Clear the input field
    taskInput.value = '';
  }
});

Step 4: Adding Event Listeners

Now, let's add event listeners to the "Delete" buttons to remove tasks from the list when clicked.

taskList.addEventListener('click', (event) => {
  if (event.target.tagName === 'BUTTON') {
    // Remove the task item
    event.target.parentNode.remove();
  }
});

Step 5: Completing and Deleting Tasks

To enhance the functionality of your to-do list, you can add a feature to mark tasks as completed.

taskList.addEventListener('click', (event) => {
  if (event.target.tagName === 'BUTTON') {
    const taskItem = event.target.parentNode;
    const isCompleted = taskItem.classList.contains('completed');
    
    if (!isCompleted) {
      taskItem.classList.add('completed');
      event.target.textContent = 'Undo';
    } else {
      taskItem.classList.remove('completed');
      event.target.textContent = 'Delete';
    }
  }
});

And there you have it! You've successfully built an interactive to-do list application using DOM manipulation and event handling.

Resources for Further Learning

In this episode, we've covered the foundational concepts of DOM manipulation, event handling, and creating dynamic web pages. As you continue your journey in web development, these skills will serve as the building blocks for crafting engaging and interactive user experiences. Stay tuned for the next episode, where we'll explore the exciting world of React, a popular JavaScript library for building user interfaces. Happy coding!

What next?

Read Episode 4

Subscribe to JS Dev Journal

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe