简体   繁体   中英

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. 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.

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

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

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

just use this ..

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

you can play around .

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.

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