Why doesn't variable span_perc's coloring change to red even though I know I've just updated it's textContent to '-28.86%'?
If I log span_perc.textContent to console it says that it's a even though that's not true because it can change it to be green and I can see it on the website.
<div >
<div >
<h5>Total Profits</h5>
<span id="profits_perc"></span>
<span id="profits_money"></span>
<Chart type="line" :data="lineData" />
</div>
</div>
</div>
</template>
<script>
import ProductService from '../service/ProductService';
import axios from 'axios';
window.onload = dostuff;
function dostuff() {
var span_perc = document.getElementById("profits_perc");
var span_money = document.getElementById("profits_money");
axios.get('http://localhost:8000/').then(response => {span_perc.textContent = response.data[2].profits_perc});
axios.get('http://localhost:8000/').then(response => {span_money.textContent = response.data[2].profits_cash});
if (span_perc.textContent == '-28.86%') {
span_perc.setAttribute("style", "color:red")
} else {
span_perc.setAttribute("style", "color:green")
}
}
CodePudding user response:
It is because the values are changed in an async way inside an XHR call, if you include your if condition inside the then block, it should work:
axios.get('http://localhost:8000/').then(response => {
span_perc.textContent = response.data[2].profits_perc;
if (span_perc.textContent == '-28.86%') {
span_perc.setAttribute("style", "color:red")
} else {
span_perc.setAttribute("style", "color:green")
}
});
CodePudding user response:
Try performing the changes within the asynchronous call.
Why the nature of async work is that while we wait for the promise to resolve as some data or an error the rest of the code will continue to execute.
function dostuff() {
var span_perc = document.getElementById("profits_perc");
var span_money = document.getElementById("profits_money");
axios.get("http://localhost:8000/").then((response) => {
span_perc.textContent = response.data[2].profits_perc;
if (span_perc.textContent == "-28.86%") {
span_perc.setAttribute("style", "color:red");
} else {
span_perc.setAttribute("style", "color:green");
}
});
axios.get("http://localhost:8000/").then((response) => {
span_money.textContent = response.data[2].profits_cash;
});
}
