I am trying to make a memory game and I want to give each image an ID so that the program can keep track of which images are the same. My function was working properly and generating the grid of random images but when I try to give the images their respective ID, random images just come out missing. Does anyone have an idea why this is happening?
function placeImages(arr){
let place = 0;
let num = 0;
let box = 1;
for(let i = 0; i < 10; i ){
num = arr[place];
const pic = document.createElement('img');
pic.id = `${num}`; //THIS IS THE PROBLEM
// pic.setAttribute('id', `${num}`); //number pics
pic.classList.toggle('pic');
pic.setAttribute('src', `./images/${num}.png`);
document.getElementById(`${box}`).appendChild(pic); //goes box by box and add image
box ;
place ;
}
console.log(arr);
}
The array is a random array of 10 numbers 1-5 only repeating once like {1, 3 , 2, 5, 5, 3, 2, 1, 4, 4}
The first image is with "pic.id = ${num}
;" commented out and the second one it is not commented out. I just started learning so sorry if the code is hard to understand.
result without id result with id
CodePudding user response:
use setAttribute().
change
pic.id
to
pic.setAttribute("id", `${num}`);
CodePudding user response:
So what I think this comes down to is that the ID attribute should be completely unique to each HTML element on a page. However, your code has multiple IDs that are the same. In the image you posted that was not displaying images it was where it was trying to give you one element with the ID of ${box} on line12. You expect this to be your div to place an image but instead, it probably got an image element that you created in a previous iteration of the loop. That is my guess and I hope that helps.
Take away: Keep IDs unique to every HTML Element!
What I recommend doing is something like this:
pic.id = `pic-${num}-${i}`;
Which will do something like this:
<img src="4.png" id="pic-4-2">
This way every ID will be unique because images will be prefixed with "pic" and postfixed with the iteration number. Then later in your code, you can splice out the middle number to match them to another image.