Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the text color with Javascript depending on the number

Tags:

javascript

I need to change the text color to red if the answer is '7' and to green if it's '13' or '24'. I've tried several different things but I can't seem to get it to work. I don't know if someone knows what I'm doing wrong, but any help would be appreciated.

do {
  var luckyNumber = prompt('What is your lucky number?', "");
  luckyNumber = parseInt(luckyNumber, 10);
} while (isNaN(luckyNumber));


if (luckyNumber == 7) {
  document.write("<p>Hey, 7 is my lucky number too!</p>").style.color = "red";
} else
if (luckyNumber == 13 || luckyNumber == 24) {
  document.write("<p>Wooh. " + luckyNumber + "? That's an unlucky number!</p>").style.color = "green";
} else {
  document.write("<p>The number " + luckyNumber + " is lucky for you!</p>");
}
like image 234
Mary Smith Avatar asked Feb 09 '18 15:02

Mary Smith


2 Answers

The issue is because document.write() doesn't return an element which you can call style.color on. This is why you see the error in the console. You should also avoid the use of document.write anyway as it's extremely bad practice.

Instead, use document.createElement() to add your new elements to the DOM. From there you can simply add classes to them which apply the required colours through CSS rules. Something like this:

do {
  var luckyNumber = parseInt(prompt('What is your lucky number?', ""), 10);
} while (isNaN(luckyNumber));

var p = document.createElement('p');
document.body.appendChild(p);

if (luckyNumber == 7) {
  p.textContent = 'Hey, 7 is my lucky number too!';
  p.classList.add('red');
} else
if (luckyNumber == 13 || luckyNumber == 24) {
  p.textContent = `Wooh. ${luckyNumber}? That's an unlucky number!`;
  p.classList.add('green');
} else {
  p.textContent = `The number ${luckyNumber} is lucky for you!`;
}
.red { color: #C00; }
.green { color: #0C0; }
like image 69
Rory McCrossan Avatar answered Sep 30 '22 07:09

Rory McCrossan


What about using an inline style attribute instead?

do {
  var luckyNumber = prompt('What is your lucky number?',"");
  luckyNumber = parseInt(luckyNumber, 10);
} while (isNaN(luckyNumber));

if (luckyNumber == 7) {
  document.write("<p style='color:red;'>Hey, 7 is my lucky number too!</p>");
} else if (luckyNumber == 13 || luckyNumber == 24) {
  document.write("<p style='color:green;'>Wooh. " + luckyNumber + "? That's an unlucky number!</p>");
} else {
  document.write("<p>The number " + luckyNumber + " is lucky for you!</p>");
}
like image 32
Louys Patrice Bessette Avatar answered Sep 30 '22 07:09

Louys Patrice Bessette