I am developing a webpage containing the functionality of changing the image of a html page on reloading it according to a random number generated. I’ve tried it out using two methods:
In the first method I used querySelectorAll property of DOM and in second method I used document.getElementsByClassName(“”);.
But in the first method the image changes according to the random number but in the second method the image doesn’t change and it sticks with the first image. Ideally both codes should achieve the same function but they are not. Can anyone explain why?
First Method:
var randomNumber1 = Math.floor(Math.random() * 6) + 1;
var randomNumber2 = Math.floor(Math.random() * 6) + 1;
randomimage_1 = "images/dice" + randomNumber1 + ".png";
randomimage_2 = "images/dice" + randomNumber2 + ".png";
var image1 = document.querySelectorAll("img")[0];
image1.setAttribute("src", randomimage_1);
document.querySelectorAll("img")[1].setAttribute("src", randomimage_2);
Second Method:
var randomNumber1 = Math.floor(Math.random() * 6) + 1;
var randomNumber2 = Math.floor(Math.random() * 6) + 1;
randomimage_1 = "images/dice" + randomNumber1 + ".png";
randomimage_2 = "images/dice" + randomNumber2 + ".png";
const image1 = document.getElementsByClassName("img1");
const image2 = document.getElementsByClassName("img2");
image1.src = randomimage_1;
image2.src = randomimage_2;
Venu Sai is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.