I have an array of image elements. Each image has a specific alt value:
<img src="dice1" alt="1" onclick="change(this);">
<img src="dice2" alt="2" onclick="change(this);">
etc,etc,etc.
I want to loop through the array, and change an image based on its alt value. In this case, when an image is clicked, it will be replaced by the image whose alt value corresponds to a randomly generated number from 1 to 6, as the code attempts to demonstrate:
function change(diceToChange) {
var imgArray = getElementsByTagName("img");
var randNum = Math.floor(Math.random() * 6) + 1;
var i;
for (i = 0; i < imgArray.length; i++) {
**if alt value of imgArray[i] equals randNum** { <-- something like this
diceToChange.style.display = "none";
imgArray[i].style.display = "block";
}
}
}
Is this even possible using javascript? What statement would make this work?
Use getAttribute
function change(diceToChange) {
var imgArray = getElementsByTagName("img");
var randNum = Math.floor(Math.random() * 6) + 1;
var i;
for (i = 0; i < imgArray.length; i++) {
if (imgArray[i].getAttribute('alt') == randNum) {
diceToChange.style.display = "none";
imgArray[i].style.display = "block";
}
}
}