PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

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

 October 15, 2022     dom, javascript, removechild     No comments   

Issue

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>



Answered By - connexo
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing