DEV Community

Cover image for JavaScript DOM Manipulation: How to Create and Remove HTML Elements Dynamically
WISDOMUDO
WISDOMUDO

Posted on

JavaScript DOM Manipulation: How to Create and Remove HTML Elements Dynamically

In modern web development, JavaScript plays a crucial role in making web pages interactive and dynamic. One of the most essential features of JavaScript is DOM manipulation, which allows you to modify the structure, content, and style of a webpage in real-time. By manipulating the DOM, you can dynamically create and remove HTML elements, making your website more engaging for users.

For beginners, understanding how to create and remove HTML elements dynamically is a foundational skill. It enables you to create interactive user experiences, such as dynamically generating lists, adding form fields, or updating content based on user actions.

What You'll Learn

By the end of this guide, you’ll be able to:

  • Understand the DOM and how JavaScript interacts with it.
  • Dynamically create new HTML elements on the fly.
  • Remove existing elements based on specific conditions.
  • Apply these techniques to real-world use cases, like adding items to a shopping cart or building a dynamic to-do list.

Understanding the DOM and Selecting Elements

The Document Object Model (DOM) serves as a programming interface for both HTML and XML documents. It represents the page as a tree structure, where each node corresponds to an element or a piece of content in the HTML document. JavaScript interacts with the DOM to manipulate these elements and their content.

Selecting DOM Elements

Before you can create or remove elements, you must first select the existing elements. You can do this using various DOM methods. Here are the most common methods for selecting elements:

let elementById = document.getElementById('myElement'); // By ID
let elementsByClass = document.getElementsByClassName('myClass'); // By Class
let elementsBySelector = document.querySelector('.myClass'); // Using a CSS selector
let allElements = document.querySelectorAll('div'); // Select all div elements
Enter fullscreen mode Exit fullscreen mode

These methods allow you to select elements on the page for further manipulation, such as appending new elements or removing existing ones.

Dynamically Creating HTML Elements

JavaScript allows you to create new HTML elements using the createElement() method. After creating an element, you can modify its properties, such as its content, class, or attributes, before appending it to the DOM.

Example: Creating a New div Element

Let’s start by creating a new div element and appending it to the body of the webpage.

// Create a new div element
let newDiv = document.createElement('div');
// Add content inside the div
newDiv.innerHTML = 'This is a dynamically created div';
// Add a class to the div for styling
newDiv.classList.add('new-class');
// Append the new div to the body
document.body.appendChild(newDiv);
Enter fullscreen mode Exit fullscreen mode

What’s Happening:

  • document.createElement('div') creates a new div element.
  • .innerHTML sets the content of the new element.
  • .classList.add('new-class') assigns a class to the div for styling purposes.
  • .appendChild(newDiv) adds the newly created div to the body of the webpage.

Example: Creating a New List Item

Let’s say you have a list of tasks and want to dynamically add a new list item. Here’s how you can do that:

HTML Source code:

<ul id="taskList">
<li>Task 1</li>
<li>Task 2</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

JavaScript Source Code:

// Select the list
let taskList = document.getElementById('taskList');
// Create a new list item
let newItem = document.createElement('li');
// Set the content of the list item
newItem.textContent = 'Task 3';
// Append the new item to the list
taskList.appendChild(newItem);
Enter fullscreen mode Exit fullscreen mode

This will remove the element with the ID elementToDelete from the page.

Example: Removing a Child Element with removeChild()

If you want to remove a specific child element from its parent, use removeChild(). For example, to remove the second item in a list:

// Select the list and the child element
let list = document.getElementById('taskList');
let itemToRemove = list.getElementsByTagName('li')[1]; // Remove second item
// Remove the selected item
list.removeChild(itemToRemove);
Enter fullscreen mode Exit fullscreen mode

This removes "Task 2" from the list.

Real-World Applications

Now that you know how to create and remove elements, let’s take a look at a few practical applications where these techniques come in handy.

Example 1: Adding New Form Fields

If you are building a form where users can dynamically add fields, JavaScript can help you create input elements in response to user actions.

let form = document.getElementById('form');
let addButton = document.getElementById('addFieldButton');
addButton.addEventListener('click', () => {
let newInput = document.createElement('input');
newInput.type = 'text';
newInput.placeholder = 'New Input Field';
form.appendChild(newInput);
});
Enter fullscreen mode Exit fullscreen mode

Example 2: Building a Dynamic To-Do List

Creating a dynamic to-do list where users can add and remove tasks is a great way to practice DOM manipulation.

let addButton = document.getElementById('addTaskButton');
let taskList = document.getElementById('taskList');
addButton.addEventListener('click', () => {
let newTask = document.createElement('li');
newTask.textContent = 'New Task';
taskList.appendChild(newTask);
});
Enter fullscreen mode Exit fullscreen mode

You can also use removeChild() to allow users to delete tasks dynamically.

Conclusion

Mastering JavaScript DOM manipulation is essential for creating interactive and dynamic web applications. The ability to create and remove HTML elements in response to user actions gives you full control over your webpage's content. Whether you're building forms, to-do lists, or adding interactive features, these techniques will help you make your websites more responsive and engaging.

Now that you know how to select elements, create new ones, and remove old ones, you’re well on your way to building modern, interactive web applications. Keep experimenting with these techniques, and you’ll gain the confidence to tackle more complex DOM tasks.

You can reach out to me via LinkedIn

Top comments (0)