javascriptdomremovechild

Why are div elements not re-indexed after removing one of them with JavaScript?


I want to remove a div with the index == 0 each time I click on one of the elements with the class .slide.

It works the first time, but when I try again, the code tries to remove the element that has been previously removed, but I can still log the element to the console.

I thought that index "0" will be assigned to the next div sharing the same class, so the next time I click, this next div would be deleted.

What am I missing here?

Here is my code:

    let slides = document.querySelectorAll(".slide")
     
    slides.forEach((el) => {
        el.addEventListener("click", () => {
            // remove the first div 
            slides[0].remove() 

            // the element above has been removed, but I still can log it out (?)
            // and it seems to keep the index [0]       
            console.log(slides[0])
        })
    })

Solution

  • This will do exactly what you expect - and will only get from the live HTMLCollection that getElementsByClassName returns:

    let slides = document.getElementsByClassName("slide")
    
    for (const slide of slides) {
      slide.addEventListener("click", () => {
        // remove the first div 
        slides[0].remove()
        console.log(slides[0])
      })
    }
    <div class="slide">0</div>
    <div class="slide">1</div>
    <div class="slide">2</div>
    <div class="slide">3</div>
    <div class="slide">4</div>
    <div class="slide">5</div>