Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
How to restore the initial state of <ul>?

I have some list like this:

<ul id='list'>
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
</ul>

I want to be capable to restore that list after some manipulation in future, so I save that:

let ul_list = document.getElementById('list');
let items = document.getElementsByTagName('li');
let li_items = [];
for (var i = 0 ; i < items.length; i++) {
        let li = document.createElement('li');
        let text = document.createTextNode(items[i].innerHTML);
        li_items.push(li.appendChild(text));
    }

and I create function to restore:

function restoreList(){
    while (ul_list.firstChild) {
        ul_list.removeChild(ul_list.firstChild)
    };

    for (var i = 0 ; i < li_items.length; i++) {
        ul_list.appendChild(li_items[i])
    };
}

But using this function I don't get marked list, only three words in a row:

FirstSecondThird

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

i think the problem are when creating the DOM, right in the li_items.push you shouldn't put the append child inside the .push, because it will return DocumentFragment.

for (var i = 0 ; i < items.length; i++) {
    let li = document.createElement('li');
    let text = document.createTextNode(items[i].innerHTML);
    li.appendChild(text)
    li_items.push(li);
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

The problem is that when you write:

li_items.push(li.appendChild(text));

you are pushing to the array li_items the return value of the appendChild(text) function.

From the appendChild() docs:

Return value

A Node that is the appended child (aChild), except when aChild is a DocumentFragment, in which case the empty DocumentFragment is returned.

So, what you are really pushing to the array (and afterwards inserting again inside <ul>) is not the whole <li> element but only the textNode.

Simply change your loop to:

for (var i = 0 ; i < items.length; i++) {
    let li = document.createElement('li');
    li.innerHTML = items[i].innerHTML;
    li_items.push(li);
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda