Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
how to delete dynamic created li by id?

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);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda