Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
salida .appendChild en elementos <li> y <span> dentro de una función de mapa

Estoy almacenando los elementos pendientes en una matriz de objetos. Quiero mapear la matriz para obtener los elementos HTML. Puedo hacer esto usando innerHTML pero quiero hacerlo con createElement .

Espero una salida <li><span>TEXT</span></li> pero solo span . Parece que agregar no funciona.

Código HTML :

 <div class="todo"> <h1>Todo</h1> <form name="todo--form"> <input type="text" name="todo--input" /> <button type="submit" name="todo--submit" class="p-2 bg-slate-500 rounded" > Add </button> </form> <ul class="todo--list"></ul> </div>

Código JS:

 const addTodoForm = document.querySelector(`[name="todo--form"]`); const todoList = document.querySelector('.todo--list'); const todos = []; // function getLabel() {} function handleSubmit(e) { e.preventDefault(); const text = this.querySelector(`[name="todo--input"]`).value; const item = { text: text, finished: false, }; if (text) { todos.push(item); addTodoForm.reset(); const todoItems = todos.map((todo, i) => { let newSpan = document.createElement('span'); let newLi = document.createElement('li'); newSpan.textContent = todo.text; let newEl = newLi.append(newSpan); return newEl; }); console.log(todoItems); todoList.append(...todoItems); } return; } addTodoForm.addEventListener('submit', handleSubmit);

Obtengo solo <span><span> como salida.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

 const todoItems = todos.map((todo, i) => { let newSpan = document.createElement('span'); let newLi = document.createElement('li'); newSpan.textContent = todo.text; let newEl = newLi.append(newSpan); return newLi; });
about 4 years ago · Juan Pablo Isaza Report

0

Cuando se envía el <form> , solo se agrega un elemento a la lista a la vez, por lo que no es necesario crear una matriz de un solo elemento. Por cierto, los controladores de eventos (funciones que están vinculadas a un evento) no devuelven valores como lo hace una función normal, pero hay formas indirectas de obtener valores de ellos (como desde su código OP, esa matriz fuera de la función empujando objetos).

Los detalles se comentan en el ejemplo.

 // Reference <form> const form = document.forms.todo; // Reference <ul> const list = document.querySelector('.list'); // Define array for storage let tasks = []; // Bind "submit" event to <form> form.onsubmit = handleSubmit; // Event handlers passes Event Object by default function handleSubmit(e) { // Stop default behavior during a "submit" e.preventDefault(); // Reference all form controls const IO = this.elements; /* Define {item} Add current timestamp to object {item} Add <input> text to {item} Add {item} to [tasks] Clear <input> */ let item = {}; item.log = Date.now(); item.task = IO.data.value; tasks.push(item); IO.data.value = ''; /* Create <time> Assign timestamp <time> Convert timestamp into a readable date and time Add formatted datetime as text to <time> */ const log = document.createElement('time'); log.datetime = item.log; let date = new Date(item.log); log.textContent = date.toLocaleString(); /* Create <output> Add text of <input> to <output> */ const txt = document.createElement('output'); txt.value = item.task; /* Create <button> Add type, class, and the text: "Delete" to <button> */ const btn = document.createElement('button'); btn.type = 'button'; btn.className = 'delete'; btn.textContent = 'Delete'; // Create <li> const li = document.createElement('li'); // Append like crazy li.append(log); li.append(txt); li.append(btn); list.append(li); console.log(tasks); }
 html { font: 300 2ch/1.2 'Segoe UI'; } input, button { font: inherit; } output { display: inline-block; margin: 0 8px 8px; } button { cursor: pointer; } .as-console-row::after { width: 0; font-size: 0; } .as-console-row-code { width: 100%; word-break: break-word; } .as-console-wrapper { max-height: 30% !important; max-width: 100%; }
 <form id='todo'> <fieldset> <legend>ToDo List</legend> <input id='data' type="text" required> <button class="p-2 bg-slate-500 rounded">Add</button> <ul class="list"></ul> </fieldset> </form>

about 4 years ago · Juan Pablo Isaza Report

0

En este bloque de código, creo que la variable newEl que se está creando no es correcta. Intente cambiar newLi.append(newSpan) a newLi.appendChild(newSpan)

Esto también se enumera a continuación

 if (text) { todos.push(item); addTodoForm.reset(); const todoItems = todos.map((todo, i) => { let newSpan = document.createElement('span'); let newLi = document.createElement('li'); newSpan.textContent = todo.text; let newEl = newLi.appendChild(newSpan); return newEl; }); console.log(todoItems); todoList.append(...todoItems); } return;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!