If a div contains a specific string of text, edit

2020-07-27 02:56发布

I'd love some help with a simple jQuery script that searches for a specific string of text. If that text exists, then manipulate the containing div's css. The HTML would look like:

<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. Please let me know if this is unclear. Thanks in advance!

CHeers.

4条回答
在下西门庆
2楼-- · 2020-07-27 02:57

use :contains selector in Jquery .

$(".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

查看更多
Rolldiameter
3楼-- · 2020-07-27 03:10

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

As Zword suggested, use filter. This solution is the fastest. JSPerf

查看更多
对你真心纯属浪费
4楼-- · 2020-07-27 03:11

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

查看更多
放我归山
5楼-- · 2020-07-27 03:14

just use this ..

$(".container div:contains('Very important text')").parent().css("height","300");

you can play around .

查看更多
登录 后发表回答