Skip to content
Advertisement

How can I create separate list items from local storage items and show them in to do list?

Here you can see a picture of the problem: ProblemInToDoList

To Do App works fine but when the app should bring saved list items from the local storage, the app puts them all in the same “li” element as you can see from the picture. The list items should be in separate “li” elements so the app would be fine. How can I put every list item in separate “li” elements?

The entire code can be found in JS Bin and you can try it there. I have tried many solutions but none of them works correctly. Those solutions that I have tried are in JS Bin but I have commented them.

Here is the problem point that you can also find in JS Bin:

let newLi1 = $("<li></li>");

for (i = 0; i < localStorage.length; i++) {
    x = localStorage.key(i);
    newLi1.append(localStorage.getItem(x)).append("<button class='delete'>x</button>").append(<br>");
    $("#list").append(newLi1);
}

Advertisement

Answer

That is due to your logic. Before the loop you create a listelement li called newLi1. In each iteration you keep adding the content of localStorage.getItem(x) which is a text, to that item. What you need to do instead is creating a new li on each iteration. So just move let newLi1 = $("<li></li>"); inside the loop and you are good to go.

//REM: Fake localstorage
var _localStorage = ['test1', 'test2', 'test3'];

for (i = 0; i < _localStorage.length; i++) {
    //x = _localStorage.key(i);
    
    //REM: Create a new list item on each iteration
    let newLi1 = $("<li></li>");
    newLi1.append(_localStorage[i]).append("<button class='delete'>x</button>").append("<br>");
    //newLi1.append(_localStorage.getItem(x)).append("<button class='delete'>x</button>").append(<br>");
    $("#list").append(newLi1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id = 'list'></ul>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement