Hi, I have a list (li items) these are feeding by a text area
I be able add this item list in my local storage and I be able remove them from the dom and from the localstorage as well
but when I load my page my List from de dom is updated their id number
but my localstorage keeps with the old order, I want to update my localstorage when te page is charged, in this way both list items and localstorage array could have the same id between them
e.g : [{"id":0,"com":"1"},{"id":1,"com":"1"},{"id":3,"com":"1"}]
I want update this like this when the page is charged: [{"id":0,"com":"1"},{"id":1,"com":"1"},{"id":2,"com":"1"}]
this is my code
const listaTweets = document.getElementById('lista-tweets');
let li;
let comment;
evenListeners();
function evenListeners() {
document.querySelector('#formulario').addEventListener('submit', addTweet);
listaTweets.addEventListener('click', deleteComment);
document.addEventListener('DOMContentLoaded', localStorageDone)
}
function addTweet(e) {
e.preventDefault();
comment = document.getElementById('tweet').value;
if(comment) {
createLi(comment)
addCommentLocalStorage(comment)
}
}
function createLi(comment) {
const deleteButton = document.createElement('a');
deleteButton.classList = 'delete-comment';
deleteButton.innerText = 'x';
li = document.createElement('li');
li.innerText = comment;
li.appendChild(deleteButton);
listaTweets.appendChild(li);
if (li) {
for (let i = 0; i < listaTweets.children.length; i++) {
li.setAttribute('id', + i)
}
}
}
function deleteComment(e) {
e.preventDefault();
li = e.target.parentElement;
if(e.target.className === 'delete-comment') {
li.remove();
deleteCommentLocalStorage()
}
}
function addCommentLocalStorage(comment) {
let arrayComments;
let id;
arrayComments = getFromLocalStorage();
arrayComments.length === 0 ? id = 0 : id = (arrayComments[arrayComments.length - 1].id) + 1
let object = {
id: id,
com: comment
}
arrayComments.push(object)
localStorage.setItem('comments', JSON.stringify(arrayComments))
}
function getFromLocalStorage() {
let arrayComments;
if(localStorage.getItem('comments') === null) {
arrayComments = []
} else {
arrayComments = JSON.parse(localStorage.getItem('comments'))
}
return arrayComments
}
function localStorageDone() {
let arrayComments;
arrayComments = getFromLocalStorage();
arrayComments.forEach(function(comment){
createLi(comment.com)
})
}
function deleteCommentLocalStorage() {
let arrayComments = getFromLocalStorage();
arrayComments.forEach( function(element) {
if (element.id == li.id) {
let i = arrayComments.indexOf(element);
arrayComments.splice(i, 1);
}
localStorage.setItem('comments', JSON.stringify(arrayComments));
});
}
thanks for any suggestions, I have with this like a 2 weeks looking a way to do that