The problem is that document.write() does not return an element that you can call style.color . This is why you see an error in the console. You should also avoid using document.write anyway, as this is a very bad practice.
Instead, use document.createElement() to add new elements to the DOM. From there, you can simply add classes to them that apply the required colors using CSS rules. Something like that:
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 an unlucky number!`; p.classList.add('green'); } else { p.textContent = `The number ${luckyNumber} is lucky for you!`; }
.red { color: #C00; } .green { color: #0C0; }
source share