Context: I'm trying to change the color of a text according to a if statement (Green if returnOfInvestment >= 0 red if this isn't true) however, it doesn't seem to be working. I've searched on SO already, but can't figure out why it isn't working as expected.
var returnOfInvestment = (netProfit / initialInvestment.value) * 100;
var valEl = document.querySelector(".number dashtext-2");
var portfolioEl = document.querySelector(".number dashtext-3");
if (returnOfInvestment >= 0) {
valEl.style.color = "green";
portfolioEl.style.color = "green";
} else {
valEl.style.color = "red";
portfolioEl.style.color = "red";
}
.dashtext-2 {
color: #27b83f !important;
}
.dashtext-3 {
color: #27b83f !important;
}
<div class="col-md">
<div class="statistic-block block">
<div class="progress-details d-flex align-items-end justify-content-between">
<div class="title">
<div class="icon"><i class="icon-bars"></i></div>
<strong><div class="valdeval"></div></strong>
</div>
<div class="number dashtext-2">
<div class="valorization"></div>
</div>
</div>
</div>
</div>
<div class="col-md">
<div class="statistic-block block">
<div class="progress-details d-flex align-items-end justify-content-between">
<div class="title">
<div class="icon"><i class="icon-pie-chart"></i></div><strong> Portfolio</strong>
</div>
<div class="number dashtext-3">
<div class="totalportfolio"></div>
</div>
</div>
</div>
</div>
.color-red { color: red; }classList.remove('.color-red'); to remove the class that changes the text-color to red or the same function with .add instead of .remove to apply the class for the red tex-color.function changeStyle() {
var returnOfInvestment = document.getElementById('input-number').value;
var valEl = document.querySelector('.random-element'),
portfolioEl = document.querySelector('.portfolio-element');
if (returnOfInvestment >= 0) {
valEl.classList.remove('color-red');
portfolioEl.classList.remove('color-red');
} else {
valEl.classList.add('color-red');
portfolioEl.classList.add('color-red');
}
}
.random-element,
.portfolio-element {
color: green;
}
.color-red {
color: red;
}
<input type="number" id="input-number" name="input-number" onchange="changeStyle()">
<h1 class="random-element">Random element</h1>
<h1 class="portfolio-element">Portfolio element</h1>
Alternativly you could add a specific class to all elements you want to change color for. Then you can use this instead:
var allEL = document.querySelectorAll('.class-name');
if (returnOfInvestment >= 0) {
allEL.forEach(el => el.classList.remove('color-red'));
} else {
allEL.forEach(el => el.classList.add('color-red'));
}
}
That will apply/remove the class of all elements with a specific class. Really helpfull if you need to apply changes to multiple elements.