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

Time:09-17

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])
        })
    })

CodePudding user response:

I believe you have deleted the element from the DOM, but have not removed it from the array. Try using the shift array method to remove the first element that you are deleting.

slides.forEach((el)=>{
    el.addEventListener("click",()=>{
        slides.shift().remove();
    })
}

CodePudding user response:

I created a container div with six divs inside. Click on a div to see it disappear, which is the behavior you are looking for.

I added index and array to the forEach and output to the console the index and the length of the array, which is really the slides NodeList. Notice which div is being removed and that the array does not change in length.

I have included two other ways to remove the divs. Please note that the slides NodeList remains the same as you are removing the divs from the DOM and not from the slides NodeList array.

let slides = document.querySelectorAll(".slide")

slides.forEach((el, index, array) => {
  el.addEventListener("click", () => {
    slides[index].remove();     // this works
    //  el.remove();            // this also works
    //  array[index].remove();  // this also works
    console.log("clicked:", index, ", length of slides:", array.length);
  })
})
.container {
  display: flex;
  flex-direction: row;
}

.slide {
  height: 100px;
  width: 100px;
  background-color: red;
  border: solid 2px black;
  font-size: 3em;
}
<div >
  <div >0</div>
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
</div>

  • Related