I’m new to Javascript.Trying to assign background images to div tag through this function:
JavaScript
x
13
13
1
(function(){
2
3
var images=['image01.jpg','image04.jpg','image12.jpg','image22.jpg','image32.jpg','image42.jpg'];
4
5
for(var index=0;index<=images.length;index++)
6
{
7
var images_class=document.querySelectorAll('.Image_c');
8
9
let image_show=images[index];
10
images_class[index].style.backgroundImage=`url(images/${image_show})`;
11
12
}})();
13
Background image Style had been correctly mapped to each div of 6 div tags. However , there is uncaught error as below:
JavaScript
1
6
1
Uncaught TypeError: Cannot read property 'style' of undefined
2
at index2.js:10
3
at index2.js:12
4
(anonymous) @ index2.js:10
5
(anonymous) @ index2.js:12
6
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
JavaScript
1
8
1
var images=['image01.jpg','image04.jpg','image12.jpg','image22.jpg','image32.jpg','image42.jpg'];
2
var x = document.querySelectorAll
3
for(var index=0;index<x.length;index++)
4
{
5
6
let image_show=images[index];
7
x[index].style.backgroundImage=`url(images/${image_show})`;
8