📖 JavaScript Creating and Removing Elements

Description

In JavaScript, dynamically creating and removing elements allows you to update the user interface in response to user actions or other events. This is an essential skill for building interactive web applications.

Core Principles

Creating Elements

To create a new HTML element, you use the document.createElement method. You can then set its attributes, content, and add it to the DOM using methods like appendChild or insertBefore.

Removing Elements

To remove an element from the DOM, you can use the removeChild method or the remove method.

Key Methods Explained

The references [element] and [parentElement] used below must first be obtained using methods like document.createElement(tagName), document.getElementById(someId), or document.querySelector(cssSelector) and assigned to a variable. This variable can then be used to call the methods shown here.

For example: let myElement = document.getElementById('someId'); can now be used to call myElement.classList.add('className'); to add a new class to the element where className is a valid CSS class name for the site.

document.createElement(tagName)
Creates an element with the specified tag name. This method returns the new element. Here, document is a reference to the HTML document, and tagName is the type of element to create (e.g., 'div').
[element].setAttribute(name, value)
Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise, a new attribute is added.
[element].classList.add(className)
Adds the specified class to the element. If the class already exists, it is not added again.
[element].classList.remove(className)
Removes the specified class from the element. If the class does not exist, no changes are made.
[parentElement].appendChild(childElement)
Adds a node to the end of the list of children of a specified parent node. If the node already exists in the document, it is moved from its current position to the new position.
[element].remove()
Removes the element from the DOM. This method does not require a reference to the parent element.

Coding Examples

Creating Elements


// Creating a new element
const newDiv = document.createElement('div'); // Create a new div element
newDiv.textContent = 'Hello, World!'; // Set the text content of the new div
newDiv.setAttribute('id', 'greeting'); // Set the id attribute of the new div
newDiv.classList.add('text-primary'); // Add a CSS class to the new div

// Adding the new element to the DOM
document.body.appendChild(newDiv); // Append the new div to the body of the document
        

Removing Elements


// Removing an element by ID
const elementToRemove = document.getElementById('greeting'); // Get the element with id 'greeting'
if (elementToRemove) {
    elementToRemove.remove(); // Remove the element from the DOM
}
        

Adding and Removing List Items


// HTML Structure
<ul id="taskList">
    <li>Task 1</li>
    <li>Task 2</li>
</ul>

// JavaScript Code
const taskList = document.getElementById('taskList'); // Get the element with id 'taskList'

// Function to add a new task
function addTask(taskName) {
    const newTask = document.createElement('li'); // Create a new list item element
    newTask.textContent = taskName; // Set the text content of the new list item
    newTask.setAttribute('class', 'task-item'); // Set the class attribute of the new list item
    taskList.appendChild(newTask); // Append the new list item to the task list
}

// Function to remove a task
function removeTask(taskName) {
    const tasks = document.querySelectorAll('.task-item'); // Get all elements with the class 'task-item'
    tasks.forEach(task => {
        if (task.textContent === taskName) {
            task.remove(); // Remove the element from the DOM
        }
    });
}

// Adding a new task
addTask('Task 3');

// Removing a task
removeTask('Task 2');
        

Putting It Into Action

Create an HTML file with the following structure and include the provided script. This script demonstrates adding and removing tasks from a list based on user input. The "Add Task" button adds a new task to the list, and clicking a task in the list removes it.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Task Manager</title>
</head>
<body>
    <div>
        <input type="text" id="taskInput" placeholder="Enter a task">
        <button id="addTaskBtn">Add Task</button>
        <ul id="taskList"></ul>
    </div>

    <script>
        const taskInput = document.getElementById('taskInput'); // Get the element with id 'taskInput'
        const addTaskBtn = document.getElementById('addTaskBtn'); // Get the element with id 'addTaskBtn'
        const taskList = document.getElementById('taskList'); // Get the element with id 'taskList'

        addTaskBtn.addEventListener('click', function() {
            const taskName = taskInput.value.trim(); // Get the value of the input field and trim whitespace
            if (taskName !== '') {
                addTask(taskName); // Add the task if the input is not empty
                taskInput.value = ''; // Clear the input field
            }
        });

        taskList.addEventListener('click', function(event) {
            if (event.target.tagName === 'LI') {
                removeTask(event.target); // Remove the task if a list item is clicked
            }
        });

        function addTask(taskName) {
            const newTask = document.createElement('li'); // Create a new list item element
            newTask.textContent = taskName; // Set the text content of the new list item
            newTask.setAttribute('class', 'task-item'); // Set the class attribute of the new list item
            taskList.appendChild(newTask); // Append the new list item to the task list
        }

        function removeTask(taskElement) {
            taskElement.remove(); // Remove the element from the DOM
        }
    </script>
</body>
</html>
        

Challenge

Modify the example to include a feature where double-clicking a task marks it as completed by adding a line-through style to the text. Use event delegation to handle the double-click event.

In order to check your learning, you should attempt to create a solution before revealing the provided solution below.


// JavaScript Code
taskList.addEventListener('dblclick', function(event) {
    if (event.target.tagName === 'LI') {
        event.target.style.textDecoration = 'line-through';
    }
});
                        

References