Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda