Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Removing Elements | DOM Manipulation
Advanced JavaScript Mastery
course content

Contenido del Curso

Advanced JavaScript Mastery

Advanced JavaScript Mastery

1. Classes
2. DOM Manipulation
3. Events and Event Handling
4. Asynchronous JavaScript and APIs

bookRemoving 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.

html

index

css

index

js

index

copy

Remove()

The remove() method is a more straightforward approach to removing an element directly without needing to access the parent node explicitly.

html

index

css

index

js

index

copy

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.

html

index

css

index

js

index

copy

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.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 10
some-alt