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){
            writingSlides += `<img src="${slidesJsonData[slide].src}" alt="${slidesJsonData[slide].alt}"/>`;
        writingSlides += `<img class="displayNone" src="${slidesJsonData[slide].src}" alt="${slidesJsonData[slide].alt}"/>`;
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)
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

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

Leave a Comment