Home > Enterprise >  How to restore the initial state of <ul>?
How to restore the initial state of <ul>?

Time:05-08

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

CodePudding user response:

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);
}

CodePudding user response:

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);
}
  • Related