Course Content
Advanced JavaScript Mastery
Advanced JavaScript Mastery
Removing Elements
In this chapter, let's dive into how to remove the elements from the DOM.
Removing Elements from the DOM
Elements can be removed dynamically using methods like removeChild()
and remove()
.
RemoveChild()
The removeChild()
method removes a specified child node from the parent node. It requires you to access both the parent and the child to remove.
index
index
index
Remove()
The remove()
method is a more straightforward approach to removing an element directly without needing to access the parent node explicitly.
index
index
index
Practical Example: Dynamic To-Do List Manager
Let's build a dynamic to-do list where users can add new tasks, insert tasks at specific positions, and remove tasks as needed.
index
index
index
Creating and Appending New Tasks:
createElement()
is used to create new<li>
items and<button>
elements dynamically when the user inputs a new task;appendChild()
adds the newly created task to the end of the list, allowing for continuous addition of tasks as the user interacts with the list.
Inserting Tasks at Specific Positions: The "Insert Task at Top" button uses insertBefore()
to add tasks to the top of the list, showing how to place elements in precise positions within the parent.
Adding Remove Functionality:
- The
addRemoveFunctionality()
function attaches an event listener to each task’s remove button, allowing each task to be deleted when the button is clicked; - This function is reused for both existing tasks and newly created tasks, ensuring consistent behavior across all tasks.
Handling Pre-Existing Elements: Existing tasks are also equipped with remove functionality by selecting all current remove buttons and attaching the necessary event listeners when the page loads.
Thanks for your feedback!