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

135
Views
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 answers
Answer question

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 Report

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 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!