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
JavaScript
x
2
1
document.getElementById("signValue").style.color = "red"
2
for example and I still can’t get it to work.
JavaScript
1
4
1
// DETERMINE THE + or - SIGN OF THE BALANCE
2
let sign = (income >= outcome) ? "$" : "-$"
3
}
4
Advertisement
Answer
This should work depending on the values of income and outcome
JavaScript
1
11
11
1
const income = 1000
2
const outcome = 500
3
let sign = (income >= outcome) ? "$" : "-$"
4
5
const element = document.getElementById("signValue")
6
if (sign === "$")
7
element.style.color = 'green'
8
else if (sign === "-$")
9
element.style.color = 'red'
10
11
element.innerHTML = sign;
JavaScript
1
1
1
<p id="signValue"></p>