I have the following dynamic HTML, and I would like to change the color of the based on text inside the last span element, in that case an "OK".
<div class="data">
<div class="fundoDiv">
<section>
<header class="textoHeader">Risk</header>
</section>
<span id="b74ac226bea04e10a80e25bbf7e529a3" style="font-family:'Arial';font-size:37px;">
<span id="f95f8aba-1b60-4174-9354-8945634b6179" viewid="f95f8aba-1b60-4174-9354-8945634b6179" class="EmbeddedMiniatureVisualization" sf-busy="false" style="position: relative; margin: 0px; padding: 0px; border: 0px; overflow: hidden;">
<span style="color: rgb(97, 100, 107); text-align: left;">OK</span></span></span>
</div>
I have tried some different approach, but none of them has gave me the correct text, so the color was not changed. In fact, the console.log(text) comand has no output. Below is the jQuery I’m using for that.
$(".fundoDiv span.EmbeddedMiniatureVisualization:last-child").each(function() {
var text = $(this).text()
console.log(text)
if (text = 'OK') {
$('div.fundoDiv').css("background-color", "green");
} else {
$('div.fundoDiv').css("background-color","red");
}
});
Any help will be highly appreciated.
Marcio
3
Answers
You forgot to trim your text to remove white spaces and compare instead of an assignment:
Use
$(".fundoDiv span.EmbeddedMiniatureVisualization:last-child").text().trim()
Inside
if
You are not comparing, you are doing an assignment so fix that. (=
is assignment and==
or===
used for comparison)Trim the text so that in case any white space is there then they will get neglected while comparison.
You need to use
.closest()
as well to get the correspondingfundoDiv
div after the comparison becomes successful or fails. (because you are looping over the span insidefundoDiv
not on thefundoDiv
itself so$(this)
will reflect<span>
actually)Working snippet:
In case your span with the class
EmbeddedMiniatureVisualization
contains multiple spans, and you want to search and match each of them then do like below: