As a newcomer to the world of Javascript, I am currently working on creating a memory game. However, I seem to be encountering some issues with getting this particular piece of code to function correctly. My goal is to select a random element from my ids
array, remove it from the array, and then use that value to assign it to an element in the cards array. The code snippet I have come up with so far (updated version) looks like this:
const cards = document.querySelectorAll(".memory-card");
let ids = ["1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6"];
function idHandler() {
let rand = Math.floor(Math.random() * ids.length);
let x = ids.splice(rand, 1)[0];
cards[x].setAttribute("id", x);
}
cards.forEach(mapIds);
In response to a request for HTML elements:
<div class="memory-card" id="1">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="1">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="2">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="2">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="3">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="3">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="4">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="4">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="5">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="5">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="6">
<img src="../assets/turned.png" class="front-face">
</div>
<div class="memory-card" id="6">
<img src="../assets/turned.png" class="front-face">
</div>