Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I change the color of an element of an array with javascript?

I have to generate a random poker card with html/javascript/css. How do I make the hearts and diamonds appear red? this is my code

window.onload = function() {
  let generateRandomNumber = () => {
    let numbers = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
    let indexNumber = Math.floor(Math.random() * numbers.length);
    return numbers[indexNumber];
  };
  let generateRandomSuit = () => {
    let suits = ["♦", "♥", "♠", "♣"];
    let indexSuit = Math.floor(Math.random(suits) * suits.length);
    return suits[indexSuit];
  };
  document.querySelector("#number").innerHTML = generateRandomNumber();

  var allSuits = generateRandomSuit();
  document.querySelector("#top").innerHTML = allSuits;
  document.querySelector("#bottom").innerHTML = allSuits;
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Set the class of the element depending on the suit symbol depending on the suit.

var allSuits = generateRandomSuit();
document.querySelector("#top").innerHTML = allSuits;
document.querySelector("#bottom").innerHTML = allSuits;
let colorClass = allSuits == '♦' || allSuits == '♥' ? 'red' : 'black';
document.querySelector("#top").classList.add(colorClass);
document.querySelector("#bottom").classList.add(colorClass);
.red {
  color: red;
}

.black {
  color: black;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading