0% encontró este documento útil (0 votos)
26 vistas8 páginas

Manipulación Del DOM Con JavaScript

Este laboratorio práctico enseña la manipulación del DOM con JavaScript a través de la creación de una aplicación de lista de tareas. Los participantes aprenderán a agregar, editar y eliminar tareas utilizando métodos como document.createElement(), appendChild() y removeChild(). Al finalizar, los estudiantes habrán adquirido habilidades esenciales para desarrollar aplicaciones web interactivas.

Cargado por

ferleonmoloney
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
26 vistas8 páginas

Manipulación Del DOM Con JavaScript

Este laboratorio práctico enseña la manipulación del DOM con JavaScript a través de la creación de una aplicación de lista de tareas. Los participantes aprenderán a agregar, editar y eliminar tareas utilizando métodos como document.createElement(), appendChild() y removeChild(). Al finalizar, los estudiantes habrán adquirido habilidades esenciales para desarrollar aplicaciones web interactivas.

Cargado por

ferleonmoloney
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 8

Laboratorio práctico: Manipulación del

DOM con JavaScript

## Tiempo estimado: 45 minutos

Introducción
El Modelo de Objetos de Documento (DOM) representa la estructura de un documento HTML
como un objeto, lo que permite interactuar con el contenido, la estructura y los estilos de las
páginas web y modificarlos dinámicamente. JavaScript proporciona diversos métodos de
manipulación del DOM que permiten a los desarrolladores crear páginas web dinámicas e
interactivas. En este laboratorio, aprenderá a manipular el DOM con JavaScript para crear una
aplicación de lista de tareas.

Objetivos
Al finalizar este laboratorio, usted:

Comprenda cómo utilizar métodos de manipulación del DOM como


document.createElement(), appendChild(), yremoveChild()
Agregar, editar y eliminar elementos dinámicamente en una página web
Cree una aplicación de lista de tareas interactiva donde las tareas se puedan gestionar en
tiempo real

Ejercicio 1: Comprensión del código de inicio


En este ejercicio, crearás la estructura básica de una aplicación de lista de tareas con tres
botones: Añadir tarea , Eliminar tarea y Editar tarea . Este código sentará las bases de la
aplicación y la mejorarás en ejercicios posteriores añadiendo funcionalidad a estos botones.

Crea un nuevo archivo llamadoindex.html

Copie el código proporcionado a continuación e insértelo en el index.htmlarchivo

Estructura básica de HTML

<!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>
<style>
/* Styles the main container of the to-do list */
.todo-container {
width: 300px;
margin: 50px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}

/* Removes default list styling for the to-do list */


.todo-list {
list-style-type: none;
padding: 0;
}
/* Styles each list item in the to-do list */
li {
margin: 10px 0;
display: flex;
justify-content: space-between;
align-items: center;
}
/* Adds spacing for buttons in list items */
button {
margin-left: 10px;
}
</style>
</head>
<body>
<div class="todo-container">
<h1>To-Do List</h1>
<!-- Input field to add new tasks -->
<input type="text" id="taskInput" placeholder="Add a new task">

<!-- Button to add a new task to the list -->


<button class="add-btn" onclick="addTask()">Add Task</button>

<!-- Unordered list to display the tasks -->


<ul class="todo-list" id="todoList"></ul>
</div>
<script>
// Placeholder for functionality to be added in future exercises
</script>
</body>
</html>

Explicación del código

1. Estructura HTML:

El <ul>con el id="todoList"contendrá la lista de tareas.


El <input>campo con id="taskInput"permite a los usuarios ingresar nuevas tareas.
Hay un botón para activar la adición de tareas, pero la funcionalidad se
implementará en los siguientes ejercicios.
2. Estilo CSS:

La .todo-containerclase se utiliza para darle estilo al contenedor de la lista de tareas


pendientes, centrándolo y agregando relleno y bordes para lograr una apariencia
limpia.
La .todo-listclase aplica estilo a la lista desordenada y a lilos elementos se les
asignan márgenes y estilos flexbox para alinearlos perfectamente.

3. Marcador de posición de JavaScript:

La sección de script contendrá la lógica para interactuar con el DOM, como agregar
tareas, eliminar tareas y editar tareas.

Inicie la página web utilizando Live Server

1. Abra su explorador de archivos y localice su archivo HTML

2. Haga clic derecho en el archivo y seleccione Abrir con Live Server

3. Aparecerá una notificación indicando que el servidor se ha iniciado en el puerto 5500

4. Haga clic en el botón debajo de la notificación o utilice la Caja de herramientas de Skills


Network . Luego, vaya a "Otros" > "Iniciar aplicación" , introduzca el puerto 5500y haga
clic en el botón de inicio resaltado en la captura de pantalla a continuación. Esto abrirá la
página web en una nueva pestaña del navegador.

Iniciar aplicación

La salida debería aparecer como se muestra en la siguiente captura de pantalla:

Exercise 2: Adding a task to the To-Do List


In this exercise, you will implement the functionality to add a new task to the list. The task will
be added dynamically when the user interacts with the page. Here's how it works:

When the user types a task into the input field and clicks the Add Task button, the task
will be added to the list.
Each task will be displayed with Edit and Delete buttons next to it.

Steps to implement the task:

1. Selecting elements:

Use document.getElementById('taskInput') to select the input field where the user will
type their task
Use document.getElementById('todoList') to select the unordered list (<ul>) where the
new tasks will be appended

2. Creating new elements:

Use document.createElement("li") to create a new list item (<li>) to hold the task
Use document.createElement("span") to create a span element that will hold the task
text
Create buttons for Edit and Delete using document.createElement("button")

3. Adding event handlers:

Link the Edit button to an event handler by setting the onclick property to a
function (e.g., editTask(span))
Similarly, link the Delete button to an event handler (e.g., removeTask(li))

4. Appending elements to the DOM:

Append the task text and the buttons to the list item (<li>) using the appendChild()
method
Append the list item (<li>) to the unordered list (<ul>) using appendChild()

5. Clearing the input field:

After adding the task to the list, clear the input field using input.value = ""

Click here to view the solution code

Output:

Reload the webpage to test the functionality. If the live server is not running, start it and
then launch the application.
Once the page is loaded, type a task in the input field and click Add Task. The task will be
added to the to-do list, appearing along with Edit and Delete buttons for each task.
Exercise 3: Editing a task in the To-Do List
In this exercise, you will implement the functionality to edit an existing task in the list. Here's
how it works:

When the user clicks the Edit button next to a task, they will be prompted to enter a new
task text.
If the user enters a valid new task text (non-empty), the task will be updated dynamically
in the list.
The task text will only be updated if the user provides a non-empty input.

Steps to implement the task:

1. Set up the Edit function:

Create a function editTask(span) where span refers to the element containing the
current task text
This function will allow you to prompt the user for new text to replace the current
task

2. Prompt the user for new text:

Inside the editTask() function, use the prompt() method to ask the user for a new
task text. You can pass the current task (span.textContent) as the default value in the
prompt.

3. Check for valid input:

After the user enters their new task, check if the input is not null and not empty. Use
newTask.trim() to ensure that the task text is not just whitespace.
4. Update the task:

If the user provides valid input, update the task by assigning the new value to
span.textContent. This will dynamically update the task in the list.

Click here to view the solution code

Output:

Reload the webpage to test the functionality. If the live server is not running, start it and
then launch the application.
Once the page is loaded, clicking on the Edit button for a specific task will display a
prompt to update the task. Make your edits and click OK to save the changes.

Exercise 4: Removing a task from the To-Do


List
In this exercise, you will implement the functionality to remove a task from the list. Here's how
it works:

When the user clicks the Delete button next to a task, the task will be removed from the
list.
The task will be removed dynamically from the unordered list.

Steps to implement the task:

1. Selecting the list:

Use document.getElementById('todoList') to select the unordered list (<ul>) that


contains the tasks
2. Removing the task:

When the user clicks the Delete button, use the removeChild() method to remove the
specific task (represented as an <li> element) from the list.

3. Removing the task element:

Pass the task (the <li> element) to the removeChild() method to remove it from the
DOM

Click here to view the solution code

Output:

Reload the webpage to test the functionality. If the live server is not running, start it and
then launch the application.
Once the page is loaded, clicking the Delete button will remove the corresponding task
from the list.

Click here to view the complete solution code

Conclusion
In this lab, you explored key DOM manipulation techniques to dynamically interact with a web
page. By completing the exercises, you gained practical experience with methods such as
createElement(), appendChild(), and removeChild(). These techniques are essential for building
interactive and user-friendly web applications, empowering you to create dynamic content
that responds to user interactions.

Author
Rajashree Patil

© IBM Corporation. All rights reserved.

También podría gustarte