I have these 3 divs:
<div class="price"><span>Free</span> </div><br/>
<div class="price"><span>$250 USD</span> </div><br/>
<div class="price"><span>$800 USD</span> </div>
The background of the divs are red by default and i want to change it to green when the span of that divs contain the word "Free".
What i tried already is this code:
$('.price > span').each(function(){
if ($('.price > span').text()==="Free"){
$('.price').css('background-color', 'green');
}
})
Why it doesn't work?
Because your selector is grabbing more than a single element , when you are using .each()
inside it's scope you can use this
to refer to the current element that's being iterated:
$('.price > span').each(function(){
if($(this).text()==="Free"){
$(this).parent(".price").css('background-color', 'green');
}
});
Spencer's looks good. If you want to do it without jquery, you can do it like this
https://jsfiddle.net/1maewneu/38/
document.querySelectorAll('.price > span').forEach(function(span) {
span.parentElement.style.backgroundColor = span.innerText === 'Free'
? 'green'
: null
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.