![](/img/trans.png)
[英]Jquery - How to find span inside div by special text and change background of span after it
[英]Change a div's background when the span inside that div contains specific text using jquery
我有以下3个div:
<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>
div的背景默认为红色,并且当该div的跨度包含单词“ Free”时,我想将其更改为绿色。
我已经尝试过的是此代码:
$('.price > span').each(function(){
if ($('.price > span').text()==="Free"){
$('.price').css('background-color', 'green');
}
})
为什么不起作用?
我的宝贝在这里
因为选择器要捕获的元素不止一个,所以在范围内使用.each()
,可以使用this
来引用要迭代的当前元素:
$('.price > span').each(function(){
if($(this).text()==="Free"){
$(this).parent(".price").css('background-color', 'green');
}
});
斯宾塞长得不错。 如果您想在没有jquery的情况下执行此操作,则可以这样做
https://jsfiddle.net/1maewneu/38/
document.querySelectorAll('.price > span').forEach(function(span) {
span.parentElement.style.backgroundColor = span.innerText === 'Free'
? 'green'
: null
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.