Skip to content
Advertisement

Change text color of a ternary operator’s expression to red or green depending on which one is executed

I’m very new to Javascript and I’ve been stuck on this problem for a few hours now and I cant seem to find out how to solve the problem.

Is there a way to have the ternary operator output “$” with green text or “-$” as red text?

The way I have it set up right now will check if the income is greater than or equal to the outcome and then add the appropriate sign in front of the balance amount. But I want the Balance and Sign to turn red if the value is negative and green if positive.

I’ve tried to assign an ID of ‘signValue’ to the $ in the HTML file and then use

document.getElementById("signValue").style.color = "red"

for example and I still can’t get it to work.

 // DETERMINE THE + or - SIGN OF THE BALANCE
         let sign = (income >= outcome) ? "$" : "-$"
}

Advertisement

Answer

This should work depending on the values of income and outcome

const income = 1000
const outcome = 500
let sign = (income >= outcome) ? "$" : "-$"

const element = document.getElementById("signValue")
if (sign === "$")
  element.style.color = 'green'
else if (sign === "-$")
  element.style.color = 'red'

element.innerHTML = sign;
<p id="signValue"></p>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement