Skip to content
Advertisement

Uncaught type error while using IIFE function

I’m new to Javascript.Trying to assign background images to div tag through this function:

(function(){
 
    var images=['image01.jpg','image04.jpg','image12.jpg','image22.jpg','image32.jpg','image42.jpg'];
    
    for(var index=0;index<=images.length;index++)
    {
    var images_class=document.querySelectorAll('.Image_c');
    
    let image_show=images[index];
    images_class[index].style.backgroundImage=`url(images/${image_show})`;
   
}})();

Background image Style had been correctly mapped to each div of 6 div tags. However , there is uncaught error as below:

Uncaught TypeError: Cannot read property 'style' of undefined
    at index2.js:10
    at index2.js:12
(anonymous) @ index2.js:10
(anonymous) @ index2.js:12

Anyone can help me understand what this error mean and how to resolve it?

Advertisement

Answer

Try to loop the queryselector object as the length of images array would me more than length of object returned from query selector

var images=['image01.jpg','image04.jpg','image12.jpg','image22.jpg','image32.jpg','image42.jpg'];
var x = document.querySelectorAll
for(var index=0;index<x.length;index++)
{

let image_show=images[index];
x[index].style.backgroundImage=`url(images/${image_show})`;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement