Zahos Gk Zahos Gk - 1 month ago 8
CSS Question

CSS and if condition in javascript

if(smaxResult<sigma){
document.getElementById('smaxResult').innerHTML = "Max strain is: " + smaxResult + "<σ(επ) text1";
} else{
document.getElementById('smaxResult').innerHTML = "Max strain is: " + smaxResult + ">σ(επ) text2";
}


Hello! i have this condition, and I want when the
(smaxResult < sigma)
occurs the
<σ(επ) text1
to turn out green or else the
>σ(επ) text2
to turn out red (I mean the color of the font).

Any advise?
thank you.

Answer

Create two classes red and green and wrap the text you want to colorize by span then add class to this span according to the condition :

var elem = document.getElementById('smaxResult');

if(smaxResult<sigma){
    elem.innerHTML = "Max strain is: " + smaxResult + "<σ(επ)  text1";
    elem.classList.add("green");
} else{
    elem.innerHTML = "Max strain is: " + smaxResult + ">σ(επ)  text2";
    elem.classList.add("red");
}

CSS :

.red{
    color: red;
}

.green{
    color: green;
}

Hope this helps.

var elem = document.getElementById('smaxResult');

var elem = document.getElementById('smaxResult');
var smaxResult = 5;
var sigma = 20;

if(smaxResult<sigma){
  elem.innerHTML = "Max strain is: " + smaxResult + " <span><σ(επ)  text1</span>";
  elem.querySelector('span').classList.add("green");
} else{
  elem.innerHTML = "Max strain is: " + smaxResult + " <span>>σ(επ)  text2</span>";
  elem.querySelector('span').classList.add("red");
}
.red{
    color: red;
}

.green{
    color: green;
}
<span id="smaxResult">Some text for test</span>