简体   繁体   中英

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(){
    var images = document.querySelectorAll("#slider img");
    images.forEach((img,index) => {
        if(index<images.length-1){
            if(!img.classList.contains("displayNone")){
                img.classList.add("displayNone");
                img[index+1].classList.remove("displayNone");
            }
        }
        else {
            img.classList.add("displayNone");
            document.querySelector("#slider img:first-of-type").classList.remove("displayNone");
        }
    });
    setTimeout("slideShow()",3000);
}
slideShow();
Now error is:
Uncaught TypeError: Cannot read property 'classList' of undefined
    at main.js:73
    at NodeList.forEach (<anonymous>)
    at slideShow (main.js:69)
    at <anonymous>:1:1

try updating your sliderImages variable before accessing it because it probably is being created before content as finished loading

You are using a for in loop that exposes other enumerable 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>

Try this

 var images = document.querySelectorAll("#slider img"); let cnt= 0 function slideShow(){ images[cnt].classList.toggle("displayNone") cnt++ if (cnt>= images.length) cnt = 0; images[cnt].classList.toggle("displayNone") } setInterval(slideShow,3000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM