Changing text color with javascript based on number

I need to change the color of the text to red if the answer is "7" and green if it is "13" or "24". I tried several different things, but I can't get it to work. I don't know if anyone 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 an unlucky number!</p>").style.color = "green"; } else { document.write("<p>The number " + luckyNumber + " is lucky for you!</p>"); } 
+5
source share
3 answers

you can change the color in the html tag by adding "style = 'color: (color)" you can use something like this

 <script> var luckyNumber = 7; 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 an unlucky number!</p>"); } else { document.write("<p>The number " + luckyNumber + " is lucky for you!</p>"); } </script> 
0
source

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; } 
+4
source

How to use 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 an unlucky number!</p>"); } else { document.write("<p>The number " + luckyNumber + " is lucky for you!</p>"); } 
+1
source

Source: https://habr.com/ru/post/1275266/


All Articles