Toggle icon for add and remove data localstorage - javascript

my cart is only work for data to localstorage but i dont know how can i make this icon switch after click add , than icon change function to remove.
i use awesome font heart for button click :
<a data-id='productID' data-link='productUrl' data-title='productItem' onclick='addItem(this)' title='add to cart'><i class='fa-regular fa-heart fa-xl'></i></a>
<table class='mt-5 table table-bordered' id='collection'></table>
here is script code
class CartItem {
constructor(url, reTitle, reId) {
this.url = url
this.reTitle = reTitle
this.reId = reId
}
}
class LocalCart {
static key = "askCollection"
static getLocalCartItems() {
let cartMap = new Map()
const cart = localStorage.getItem(LocalCart.key)
if (cart === null || cart.length === 0) return cartMap
return new Map(Object.entries(JSON.parse(cart)))
}
static addItemToLocalCart(id, item) {
let cart = LocalCart.getLocalCartItems()
if (cart.has(id)) {
} else
cart.set(id, item)
localStorage.setItem(LocalCart.key, JSON.stringify(Object.fromEntries(cart)))
updateCartUI()
}
static removeItemFromCart(id) {
let cart = LocalCart.getLocalCartItems()
if (cart.has(id)) {
cart.delete(id)
}
if (cart.length === 0)
localStorage.clear()
else
localStorage.setItem(LocalCart.key, JSON.stringify(Object.fromEntries(cart)))
updateCartUI()
}
}
function addItem(e) {
const url = e.dataset.link;
const reTitle = e.dataset.title;
const reId = e.dataset.id;
const item = new CartItem(url, reTitle, reId)
LocalCart.addItemToLocalCart(url, item)
}
function updateCartUI() {
const cartWrapper = document.querySelector('#collection')
cartWrapper.innerHTML = ""
const items = LocalCart.getLocalCartItems()
if (items === 0) return
let count = 0
for (const [key, value] of items.entries()) {
const cartItem = document.createElement('tr')
count += 1;
cartItem.innerHTML =
`
<td width="370" class="record" style="padding:5px">${value.reTitle}</td>
<td width="370" class="record" style="padding:5px">${value.reTitle}</td>
<td width="30" class="record-de"><i class="fa-regular fa-circle-minus"></i></td>
`
cartItem.querySelector('.record-de').addEventListener('click', () => {
LocalCart.removeItemFromCart(key)
})
cartWrapper.append(cartItem)
}
}
document.addEventListener('DOMContentLoaded', () => {
updateCartUI()
})
If fa-heart clicked then save to localstorare (fa-heart change from fa-regular to fa-solid)
if page reload, the fa-heart still in solid icon.
and can the fa-heart change function (toggle switch from add to remove if data has in localstorage)
i try it : https://jsfiddle.net/ceunahteuing/ypq95j3u/15/
Thanks in advance.

Related

The node to be removed is not a child of this node JavaScript

Other stack answers have failed to fix my problem because I think this occurs for different reasons. My JS code:
const addButton = document.querySelector('.addButton')
var input = document.querySelector('.input')
const draggable_list = document.getElementById('draggable-list'); //draggable_list is a ul
let itemBox;
let items;
const array = [];
const listItems = [];
let dragStartIndex;
class item {
constructor(itemName) {
this.createDiv(itemName);
}
createDiv(itemName) {
let removeButton = document.createElement('button');
removeButton.innerHTML = 'REMOVE';
removeButton.classList.add('removeButton');
draggable_list.appendChild(items);
items.appendChild(removeButton);
removeButton.addEventListener('click', () => this.remove(items);
}
async remove(item, value) {
draggable_list.removeChild(item)
}
}
async function check() {
if (input.value != '') {
array.push(input.value)
listItems.push(input.value)
array.forEach((numbers,index) => {
items = document.createElement('li')
items.setAttribute('data-index', index)
items.innerHTML = `
<div class="draggable" draggable="true">
<p class="phone-number">${numbers}</p>
<i class="fas fa-grip-lines"></i>
</div>`;
} )
new item(input.value)
input.value = ''
}
addButton.addEventListener('click', check)
When remove() is called for the first time, it successfully removes the last li element. But when it is called again, I get the following error:
Uncaught (in promise) DOMException: Node.removeChild: The node to be removed is not a child of this node
Does this work for you...
const addButton = document.querySelector('.addButton');
const input = document.querySelector('.input');
const draggable_list = document.getElementById('draggable-list');
//draggable_list is a ul
let itemBox;
let items;
const array = [];
const listItems = [];
let dragStartIndex;
class Item {
constructor(itemName) {
this.createDiv(itemName);
}
createDiv(itemName) {
let input = document.createElement('input');
input.value = itemName;
let removeButton = document.createElement('button');
removeButton.innerHTML = 'REMOVE'
removeButton.classList.add('removeButton');
draggable_list.appendChild(items);
items.appendChild(removeButton);
removeButton.addEventListener('click', (event) => {
if (event && event.target.parentElement) {
// this.remove(items));
this.remove(event.target.parentElement);
}
});
}
remove(item, value) {
draggable_list.removeChild(item);
}
}
function check() {
if (input.value != '') {
array.push(input.value);
listItems.push(input.value);
array.forEach((numbers, index) => {
items = document.createElement('li');
items.setAttribute('data-index', index)
items.innerHTML = `
<div class="draggable" draggable="true">
<p class="phone-number">${numbers}</p>
<i class="fas fa-grip-lines"></i>
</div>`;
});
new Item(input.value);
input.value = '';
}
}
addButton.addEventListener('click', check)
<button class="addButton">+</button>
<input type="text" class="input" />
<ul id="draggable-list">
</ul>
Instead of copying and pasting some convoluted code you don't understand you should try and write it yourself. Try and focus on what you require and nothing else.
Here is one way of doing it:
const [inp,btn,ul]=["input","button","ul"].map(e=>document.querySelector(e));
btn.onclick=function(){
ul.innerHTML+=`<li><p>${inp.value}</p><button>delete</button></li>`;
inp.value="";
}
ul.onclick=function(ev){
if (ev.target.tagName==="BUTTON")
ul.removeChild(ev.target.closest("li"));
}
<input type="text">
<button>add</button>
<ul></ul>

How to delete an item from an array from localstorage onclick

I have the following code. It stores the info on localstorage each time the user clicks on an "add to cart" button:
let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i++){
let button = addCartItemButtons[i]
button.addEventListener('click', addProduct)
}
function addProduct(event) {
let buttonClicked = event.target
let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')
let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
let newItem = {
'title': getTitle,
'image': getImage,
'color': getColor,
'size': getSize,
'price': getPrice,
'spanid': getSpan,
};
oldItems.push(newItem);
localStorage.setItem('newProduct', JSON.stringify(oldItems));
}
Then, i have a code that allows me to display the data the user have locally stored by creating divs and displaying the info:
let cartProducts = JSON.parse(localStorage.getItem("newProduct"))
for(let i = 0; i < cartProducts.length; i++){
let newCartProduct = document.createElement('div')
newCartProduct.classList.add('product')
newCartProduct.classList.add('cart')
const image = cartProducts[i].image
const title = cartProducts[i].title
const spanid = cartProducts[i].spanid
const color = cartProducts[i].color
const size = cartProducts[i].size
const price = cartProducts[i].price
let newCartProductContent = `
<div class="product-header cart"><img src="${image}" alt="" /></div>
<div class="product-content">
<h3 class="product-title" id="product-title">
${title}
</h3>
<div class="product-description">
<ul class="product-description-text cart">
<li>Color: <span id="${spanid}">${color} </span></li>
<li>Size: ${size} </li>
<li>Quantity: <input type="number" class="product-description-quantity" min="1" placeholder="2" value="2"></li>
</ul>
<p class="product-description-price" id="price1">
${price}
</p>
**Remove<i class="fas fa-trash"></i>**
</div>
</div>`
newCartProduct.innerHTML = newCartProductContent
let cartItems = document.getElementsByClassName('products_container_first-row')[0]
cartItems.append(newCartProduct)
}
So what i need to do now is to create a function that allows me to delete the data that it's the same which is on localstorage, each time that the user clicks on a "remove" button (in the above code is the line which has the ** ** at beginning and ending), but i cant figure out how to do this. Any ideas? Thanks!
UPDATE: i've come to this code but i get -1 as index for each element:
let addCartItemButtons = document.getElementsByClassName('product-description-add')
for (let i = 0; i < addCartItemButtons.length; i++){
let button = addCartItemButtons[i]
button.addEventListener('click', function(event){
let buttonClicked = event.target
let getTitle = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-title').innerText
let getImage = buttonClicked.parentElement.parentElement.parentElement.querySelector('.product-header img').src
console.log(getImage)
let getColor = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li span').innerText
let getSize = buttonClicked.parentElement.parentElement.querySelector('.product-description-text li select').value
let getPrice = buttonClicked.parentElement.parentElement.querySelector('.product-description-price').innerText
let getSpan = buttonClicked.parentElement.parentElement.querySelector('li span').getAttribute('id')
console.log(getSpan)
let oldItems = JSON.parse(localStorage.getItem('newProduct')) || [];
let newItem = {
'id': i+1,
'title': getTitle,
'image': getImage,
'color': getColor,
'size': getSize,
'price': getPrice,
'spanid': getSpan,
};
oldItems.push(newItem);
localStorage.setItem('newProduct', JSON.stringify(oldItems));
})
}
let cartProducts = JSON.parse(localStorage.getItem("newProduct"));
for(let i = 0; i < cartProducts.length; i++){
let newCartProduct = document.createElement('div')
newCartProduct.classList.add('product')
newCartProduct.classList.add('cart')
console.log(newCartProduct)
const id = cartProducts[i].id
const image = cartProducts[i].image
const title = cartProducts[i].title
const spanid = cartProducts[i].spanid
const color = cartProducts[i].color
const size = cartProducts[i].size
const price = cartProducts[i].price
let newCartProductContent = `
<div class="product-header cart" id="${id}"><img src="${image}" alt="" /></div>
<div class="product-content">
<h3 class="product-title" id="product-title">
${title}
</h3>
<div class="product-description">
<ul class="product-description-text cart">
<li>Color: <span id="${spanid}">${color} </span></li>
<li>Size: ${size} </li>
<li>Quantity: <input type="number" class="product-description-quantity" min="1" placeholder="2" value="2"></li>
</ul>
<p class="product-description-price">
${price}
</p>
Remove<i class="fas fa-trash"></i>
</div>
</div>`
newCartProduct.innerHTML = newCartProductContent
let cartItems = document.getElementsByClassName('products_container_first-row')[0]
cartItems.append(newCartProduct)
}
function lsdel(storage_name, value){
if (localStorage.getItem(storage_name) === null) {
} else {
var ls_data = JSON.parse(localStorage.getItem(storage_name));
var index = ls_data.indexOf(value);
console.log("selected index:"+index);
if(index == -1){
// if not matched selected index
} else {
// is matched, remove...
ls_data.splice(index, 1);
localStorage.setItem(storage_name, JSON.stringify(ls_data));
console.log(ls_data);
}
}
}
value is the ID of an element, but ls_data is an array of objects, not IDs. So ls_data.indexOf(value) will not find the object in the array. And even if value were an object, this wouldn't work because object equality is based on identical objects in memory, not comparing contents.
You need to use findIndex to match the id property of an array element.
function lsdel(storage_name, value) {
if (localStorage.getItem(storage_name) === null) {} else {
var ls_data = JSON.parse(localStorage.getItem(storage_name));
var index = ls_data.findIndex(({id}) => id == value);
console.log("selected index:" + index);
if (index == -1) {
// if not matched selected index
} else {
// is matched, remove...
ls_data.splice(index, 1);
localStorage.setItem(storage_name, JSON.stringify(ls_data));
console.log(ls_data);
}
}
}

Uncaught TypeError: Cannot read properties of undefined (reading 'isDone')

The functionality works just fine, however, I get this error in the console when clicking the trash icon while deleting the todo item.
Uncaught TypeError: Cannot read properties of undefined (reading 'isDone')
at TodoList.done_undone (script.js:68)
at HTMLLIElement.<anonymous> (script.js:104)
done_undone # script.js:68
(anonymous) # script.js:104
Here is the link to the live page: https://sarahschlueterportfolio.z22.web.core.windows.net/todolist.html
Here is my code:
HTML
<!-- Page Content -->
<div class="container">
<div class="todoHeader">
<h1>My To Do List</h1>
<input type="text" id="userInput" placeholder="Things to be done..." />
<span class="addButton" id="add_button">Add</span>
</div>
<ul id="todoListItems">
</ul>
</div>
<!-- /.container -->
JS
const todoObjectList = [];
class TodoList {
constructor(item){
this.ulElement = item;
}
add() {
const todoInput = document.querySelector("#userInput").value;
if (todoInput == "") {
alert("Please enter an item.")
} else {
const todoObject = {
id : todoObjectList.length,
todoText : todoInput,
isDone : false,
}
todoObjectList.unshift(todoObject);
this.display();
document.querySelector("#userInput").value = '';
}
}
done_undone(x) {
const selectedTodoIndex = todoObjectList.findIndex((item) => item.id == x);
todoObjectList[selectedTodoIndex].isDone == false ? todoObjectList[selectedTodoIndex].isDone = true : todoObjectList[selectedTodoIndex].isDone = false;
console.log(todoObjectList[selectedTodoIndex].isDone);
this.display();
}
deleteElement(z) {
const selectedDelIndex = todoObjectList.findIndex((item) => item.id == z);
todoObjectList.splice(selectedDelIndex,1);
this.display();
}
display() {
this.ulElement.innerHTML = "";
todoObjectList.forEach((objectItem) => {
const liElement = document.createElement("li");
const delButton = document.createElement("i");
liElement.innerText = objectItem.todoText;
liElement.setAttribute("data-id", objectItem.id);
delButton.setAttribute("data-id", objectItem.id);
delButton.classList.add("far", "fa-trash-alt");
liElement.appendChild(delButton);
delButton.addEventListener("click", function(e) {
const deleteId = e.target.getAttribute("data-id");
personalTodoList.deleteElement(deleteId);
})
liElement.addEventListener("click", function(e) {
const selectedId = e.target.getAttribute("data-id");
personalTodoList.done_undone(selectedId);
})
if (objectItem.isDone) {
liElement.classList.add("checked");
}
this.ulElement.appendChild(liElement);
})
}
}
const listSection = document.querySelector("#todoListItems");
personalTodoList = new TodoList(listSection);
document.querySelector(".addButton").addEventListener("click", function() {
personalTodoList.add()
})
I have tried looking up different solutions. One recommended putting the script at the bottom of my html instead of the top, that made no difference.
I'm fairly certain there is something wrong with the line of code before the console log in the done_undone method.
Any insight on how to clear this error would be greatly appreciated!
when you click delete you are removing element by id
deleteElement(z) {
const selectedDelIndex = todoObjectList.findIndex((item) => item.id == z);
todoObjectList.splice(selectedDelIndex,1); // element is removed from the array
this.display();
}
but done_undone is called inside of this.diaplay() in the next row
done_undone(x) {
const selectedTodoIndex = todoObjectList.findIndex((item) => item.id == x);
// selectedTodoIndex here is -1 because element is already removed
// add this condition to check if element is present in the array
if (selectedTodoIndex !== -1) {
todoObjectList[selectedTodoIndex].isDone == false ?
todoObjectList[selectedTodoIndex].isDone = true :
todoObjectList[selectedTodoIndex].isDone = false;
}
}

Unable to change DOM element style that is pass as a string

I have passed my DOM element as a string here.
function showNotes() {
let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}
let html = "";
notesObj.forEach(function(element, index) {
html += `<div class="noteCard card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Title: ${element.title}</h5>
<p class="card-text">${element.text}</p>
<a href="#" id="${index}"onclick="deleteNotes(this.id)" class="card-link" >Delete Note</a>
Important
</div>
</div>`;
});
I want to give a style to the card. When an user clicks the link "Important" (as mentioned in the DOM), the corresponding card color should be changed. So I am trying to access the "noteCard" class.
Here is my markNotes() function
function markNotes(index) {
let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}
noteStyl = document.querySelectorAll('.noteCard')[0];
noteStyl.style.color = "red";
console.log("Color should be applied")
localStorage.setItem("notes", JSON.stringify(notesObj));
showNotes();
}
I have tried the following things also but nothing works out.
noteStyl = document.getElementsByClassName('noteCard')[0]
noteStyl = document.querySelector('.noteCard')[0];
With this code, when I am clicking the link "Important" nothing is going to change except the printing of "Color should be applied".
So there must be a problem in accessing the DOM file. I am really stuck in it.
Thanks in advance
See below code and comments I added I commented your localStorage code and added my dummy code for demo.
function showNotes() {
let notes = [{
title: 'title1',
text: 'text1'
},
{
title: 'title2',
text: 'text2'
},
{
title: 'title3',
text: 'text3'
}
];
notesObj = notes;
/* if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
} */
let html = "";
notesObj.forEach(function(element, index) {
html += `<div class="noteCard card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Title: ${element.title}</h5>
<p class="card-text">${element.text}</p>
<a href="#" id="${index}"onclick="deleteNotes(this.id)" class="card-link" >Delete Note</a>
Important
</div>
</div>`;
});
document.getElementById("html").innerHTML = html; // to insert data into HTML
}
showNotes() // calling function first time
function markNotes(index) {
console.log('index', index)
/*let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}*/
noteStyl = document.querySelectorAll('.noteCard')[index];
noteStyl.style.color = "red";
console.log("Color should be applied")
localStorage.setItem("notes", JSON.stringify(notesObj));
//showNotes(); // See I have commented this code
}
<div id="html">
</div>
There is nothing wrong with accessing the DOM. I think you are trying to access an element that is not on the page.
Are you displaying the html on the page at the end of showNotes function?
You can do so by: someDiv.innerHTML = html.
Update
to access a specific card (not always the first one) maybe you can set an id for each card with its index example: card-${index}, then accessing it with .getElementById
Update #2
You are storing notesObj as an array, and in the loop (in showNotes) you are creating a static style. So you need to update the object styles in notesObj
So instead of setting the style, create a styles object:
function markNotes(index) {
let notes = localStorage.getItem("notes");
if (notes != null) {
notesObj = JSON.parse(notes);
} else {
notesObj = [];
}
if(!notesObj[index].styles) notesObj[index].styles = {};
notesObj[index].styles.color = "red";
localStorage.setItem("notes", JSON.stringify(notesObj));
showNotes();
}
Then apply it in the showNotes:
notesObj.forEach(function(element, index) {
style = "";
if(element.styles) {
console.log(element.styles);
for (let key in element.styles) {
style += `${key}: ${element.styles[key]}`;
}
}
console.log(style);
html += `<div class="noteCard card" style="width: 18rem; ${style}">
<div class="card-body">
<h5 class="card-title">Title: ${element.title}</h5>
<p class="card-text">${element.text}</p>
<a href="#" id="${index}"onclick="deleteNotes(this.id)" class="card-link" >Delete Note</a>
Important
</div>
</div>`;
});

Sort array of objects by key values and displaying them on a HTML element

I'm making a movie sorter list, you enter the title and then the rating and it will show you the movies in order by rating. I have an array of objects and I managed to sort the array by rating, but I can't find a way to actually display the array in order on the HTML DOM.
I've tried for loops and forEach's but they don't work the way I want.
const movieTitle = document.querySelector(".movie-title");
const movieRating = document.querySelector(".movie-rating");
const movieList = document.querySelector(".movie-list");
const sortBtn = document.querySelector(".btn");
let movieStorage = [];
function sendMovie() {
if(event.keyCode == 13) {
if(movieTitle.value != "" && movieRating.value != "") {
title = movieTitle.value;
rating = parseInt(movieRating.value);
movieStorage.push({
title: title,
rating: rating
});
// If rating of a is bigger than rating of b return 1, if not return -1
movieStorage.sort((a, b) => (a.rating > b.rating) ? -1 : 1);
console.log(movieStorage);
addMovieToList(title, rating);
movieTitle.value = "";
movieRating.value = "";
} else {
console.log("Fields missing");
}
}
}
function addMovieToList(title, rating) {
const div = document.createElement("div");
div.className = "list-items";
div.innerHTML = `
<div class="item-title">
<p>${title}</p>
</div>
<div class="item-rating">
<p>${rating}</p>
</div>
<div class="item-delete">
<i class="fa fa-trash trash-icon delete"></i>
</div>
`;
movieList.appendChild(div);
}
function sortByRating(element) {
for(let i = 0; i < movieStorage.length; i++) {
element.innerHTML = `
<div class="item-title">
<p>${movieStorage[i].title}</p>
</div>
<div class="item-rating">
<p>${movieStorage[i].rating}</p>
</div>
<div class="item-delete">
<i class="fa fa-trash trash-icon delete"></i>
</div>
`;
}
}
document.addEventListener("click", (e) => {
const deleteIcon = e.target;
const item = document.querySelector(".list-items");
if(deleteIcon.classList.contains("delete")) {
deleteIcon.parentElement.parentElement.remove(item);
}
})
tldr demo
After sorting the array, you need a way to reference movie divs to sort them. There are many ways to do it, what I chose is using id. When you create movie <div>, give it an ID unique for each movie name:
// Simple function to generate hash number for each string
function hashStr(stringValue) {
var hash = 0, i, chr;
if (stringValue.length === 0) return hash;
for (i = 0; i < stringValue.length; i++) {
chr = stringValue.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
const MOVIES = [
{name: "a", rating: 3},
{name: "b", rating: 6},
{name: "c", rating: 3},
{name: "d", rating: 2},
{name: "e", rating: 1},
];
function showMovies() {
const moviesDiv = document.querySelector("#movies");
for(const movie of MOVIES)
{
const id = "movie-"+hashStr(movie.name);
// If there's no element with the ID, we need to create the DIV for the movie
if(!document.querySelector("#"+id)) {
const elm = document.createElement("div");
elm.appendChild(new Text(movie.name + " ("+movie.rating+"/10)"));
elm.id = id;
elm.classList.add("movie");
moviesDiv.appendChild(elm);
}
}
}
Then, when sorting, you can reference each movie by ID:
// Sort movies using given property (eg. "name")
// The second param determines sort direction
function sortBy(property, ascending=true) {
MOVIES.sort((a,b) =>{
return cmp(a[property], b[property], ascending);
});
// Now after sorting the array, we can sort the HTML elements
const moviesDiv = document.querySelector("#movies");
let lastMovie = null;
for(const movie of MOVIES)
{
const id = "#movie-"+hashStr(movie.name);
const movieDiv = document.querySelector(id);
console.log(id, movieDiv);
// If created
if(movieDiv) {
// remove and append after last processed movie (for the first movie, this will append to top)
moviesDiv.insertBefore(movieDiv, lastMovie);
}
}
}
// Compare string and number, makes no sense for other types
function cmp(a,b, ascending=true) {
if(typeof a=='number' && typeof b == "number") {
return ascending ? a-b : b-a;
}
else if(typeof a=='string' && typeof b == "string"){
return (ascending ? 1 : -1) * a.localeCompare(b);
}
else {
return 0;
}
}
When you add a movie, you just call sort again. You will need to remember the last sorting parameters for that.
Your sort will work fine. The problem is that after you've sorted you can't just display that movie, you have to redisplay the entire list. You're almost there with your sortByRating method, but it doesn't recreate the entire list correctly. Try something like:
function showMoviesList(element) {
let innerHTML = "";
for (let i = 0; i < movieStorage.length; i++) {
innerHTML += `
<div class="item-title">
<p>${movieStorage[i].title}</p>
</div>
<div class="item-rating">
<p>${movieStorage[i].rating}</p>
</div>
<div class="item-delete">
<i class="fa fa-trash trash-icon delete"></i>
</div>
`;
}
element.innerHTML = innerHTML;
}
This resets the inner HTML of the element to the complete movie list in order every time it's called.
Now call showMoviesList(movieList) instead of calling addMovieToList in sendMovie.

Categories