简体   繁体   English

如果div包含特定的文本字符串,请编辑父级的CSS

[英]If a div contains a specific string of text, edit the parent's css

I'd love some help with a simple jQuery script that searches for a specific string of text. 我希望使用简单的jQuery脚本来搜索特定的文本字符串,以提供一些帮助。 If that text exists, then manipulate the containing div's css. 如果该文本存在,则操纵包含div的CSS。 The HTML would look like: HTML看起来像:

<div class="container">
    <div>
        <div class="heading">
            <a href="#">Very important text</a>
        </div>
    </div>
</div>

<div class="container">
    <div>
        <div class="heading">
            <a href="#">Not important at all</a>
        </div>
    </div>
</div>

<div class="container">
    <div>
        <div class="heading">
            <a href="#">Very important text</a>
        </div>
    </div>
</div>

<div class="container">
    <div>
        <div class="heading">
            <a href="#">Not important at all</a>
        </div>
    </div>
</div>

For example: If a container contains the string "Very important text" I would like to give the 'heading' class a height of 200px and its 'container' div a background of green. 例如:如果一个容器包含字符串“非常重要的文本”,我想给“标题”类赋予200px的高度,并将其“容器” div赋予绿色背景。 Please let me know if this is unclear. 如果不清楚,请告诉我。 Thanks in advance! 提前致谢!

CHeers. 干杯。

use :contains selector in Jquery . 在Jquery中使用:contains选择器。

$(".container .heading a:contains('Very important text')").each(function(i , v){
    $(this).closest(".heading").css("height" , "200px");
    $(this).closest(".container").css("background-color" , "green");
});

or simply 或简单地

$(".container .heading a:contains('Very important text')")
        .closest(".heading").css("height" , "200px")
        .closest(".container").css("background-color" , "green");

Fiddle 小提琴

You can do this: 你可以这样做:

$('.container').filter(':contains("Very important text")')
.css('background-color', 'green')
.find('.heading').css('height', '200px');

Demo: http://jsfiddle.net/AmitJoki/y82X9/1 演示: http//jsfiddle.net/AmitJoki/y82X9/1

As Zword suggested, use filter. 正如Zword建议的那样,使用过滤器。 This solution is the fastest. 该解决方案是最快的。 JSPerf JSPerf

Using filter is a faster and better option: 使用过滤器是更快,更好的选择:

$(".container .heading a").filter(":contains('Very important text')").closest(".heading").css("height","200px").closest(".container").css("background-color", "green");

Demo Fiddle 演示小提琴

See test : http://jsperf.com/so-22877172 参见测试: http : //jsperf.com/so-22877172

just use this .. 只是用这个..

$(".container div:contains('Very important text')").parent().css("height","300"); $(“。container div:contains('非常重要的文字')”)。parent()。css(“ height”,“ 300”);

you can play around . 你可以玩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM