Problem with access to dynamically created elements

I’ve asked a similar question before but that was about events related to dynamically created elements. Now I just want to change class lists of dynamically created img tags in a div. Here is what is all about, I want to create a slider that contains three images taken with src and alt attributes taken from a JSON file. Function created all three normally and as I wanted put displayNone class on every img except first. Another function should on every 3 seconds check in a loop all the dynamically created img tags for the one that does not contain displayNone class and to add to that particular img class displayNone and then to get next, or if it is last first, img and to remove his displayNone class. I created var inside function to get an array of these images. Does anybody know what the solution is?

function showSlides(slidesJsonData){ // there is no problem with this function it generates img tags when window is loaded
    var writingSlides = "";
    for (slide in slidesJsonData){
        if(slide==0){
            writingSlides += `<img src="${slidesJsonData[slide].src}" alt="${slidesJsonData[slide].alt}"/>`;
        }
        writingSlides += `<img class="displayNone" src="${slidesJsonData[slide].src}" alt="${slidesJsonData[slide].alt}"/>`;
    }
    document.querySelector("#slider").innerHTML=writingSlides;
}
function slideShow(){ // here is the problem
    var sliderImages = document.querySelectorAll("#slider img");
    console.log(sliderImages); // gives an empty array
    for(sliderImage in sliderImages){
    if(sliderImages[sliderImage].classList.contains("displayNone")){ //here is spot where the where error is generating, it's about contains and i don't know why
        //further code (removes and adds displayNone)
    }
}
    setTimeout("slideShow()",3000);
}
slideShow();
And here is error from console panel:
main.js:71 Uncaught TypeError: Cannot read property 'contains' of undefined
    at slideShow (main.js:71)
    at main.js:77

24 thoughts on “Problem with access to dynamically created elements”

  1. You are using a for in loop that exposes other properties of the element collection unrelated to element indexing. Element collections are not proper arrays but rather are array-like objects

    When you try to pass these properties to sliderImages[sliderImage] inside your loop they do not return an element with a classList property and no sub property contains which throws the error.

    Use a for loop based on length or a for of loop or sliderImages.forEach(callback)


    Simple property output example of the for in

    const li = document.querySelectorAll('li')
    
    for (let x in li) {
      if (isNaN(x)) {
        console.log(`Property "${x}" is not an element index`)
      } else {
        console.log(`Key "${x}" is an element index`)
      }
    }
    <ul>
      <li></li>
      <li></li>
    </ul>
    Reply

Leave a Comment