I have the following code
How I "paint" each 2 cards in the same color (I do a memory game)
document.addEventListener('DOMContentLoaded', () => {
function generateRandomColor() {
var randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
return randomColor;
}
var grid = document.querySelector(".grid");
for (var i = 0; i < 50; i++) {
grid.innerHTML += '<div class="card" ></div>';
var cards = document.querySelectorAll(".card");
cards[i].style.backgroundColor = generateRandomColor();
}
})
have no idea how to do pairs
2
Answers
You could increase the step in your for loop. Also, to avoid redundant lookups of all cards created so far, for up to 50 times, and then ignore up to 49 not actually used, you should the newly created element directly, like this (untested code):
Here is an example. I assumed that the colors should be distributed randomly, and not in a row every 2 cards. So the main thing here – we need to generate a pairs array to assign each color twice for random cards.