I am a beginner in javascript and I have li which is dynamically inserted by the user and is saved in an array of objects, it has its dynamic random id and I want when the user presses the element, it returns the id of the li and compare it with the movie id so I can find the index and then remove it from the array and remove the li. Thank you for your help in advance.
let n;
function deleteFilm() {
const len = listRoot.children.length;
for (let i = 0; i < len; i++) {
const element = listRoot.children[i]; // listRoot is ul
element.addEventListener('click', () => {
const idToRemove = +element.id;
index = movies.map((object) => object.movieId).indexOf(idToRemove);
console.log(index);
n = index;
});
}
console.log(n);
movies.splice(n, 1);
listRoot.children[n].remove();
if (movies[0] === undefined) {
entryText.style.display = 'block';
}
deleteModal.classList.remove('visible');
blackDrop.classList.remove('visible');
}
acceptButton.addEventListener('click', deleteFilm);
Don't assign all over again clicks (specially not inside a for loop).
Your basic logic could be simplified to this couple of lines:
const movies = [
{id:123, title:"Lorem"},
{id:456, title:"Ipsum"},
{id:789, title:"Dolor"},
];
// Retrieve a movie from array by its ID
const getMovie = (id) => movies.find(mov => mov.id === id);
// Remove a movie Object from array
const deleteMovie = (id) => movies.splice(movies.indexOf(getMovie(id)), 1);
// Task:
const movieId = 456; // The movie ID to delete
deleteMovie(movieId);
console.log(movies); // Test
Then, to delete elements from the DOM, knowing the ID was i.e: 456 all you need is to target the elements that have the data-movieid="456" like:
document.querySelectorAll(`[data-movieid="${movieId}"]`).forEach(el => el.remove());
Example:
// Utility functions:
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
const ELS = (sel, parent) => (parent || document).querySelectorAll(sel);
const EL = (sel, parent) => (parent || document).querySelector(sel);
// Task:
const getMovie = (id) => movies.find(mov => mov.id === id);
const deleteMovie = (id) => movies.splice(movies.indexOf(getMovie(id)), 1);
const createMovie = (movie) => {
const EL_li = ELNew("li", {
className: "list-item movie",
textContent: movie.title,
onclick() {
deleteMovie(movie.id);
EL_li.remove();
ELS(`[data-movieid="${movie.id}"]`).forEach(el => el.remove());
}
});
EL("#movies").append(EL_li);
};
const movies = [
{id:123, title:"Lorem"},
{id:456, title:"Ipsum"},
{id:789, title:"Dolor"},
];
movies.forEach(createMovie);
Click to delete a movie:
<ul id="movies" class="list"></ul>
<div data-movieid="456">If you click on Ipsum I will be removed too!</div>