开发者

jQuery - Apply CSS to div1 if div2 contains a certain word of text?

With jQuery how can I apply css to a div, if another div contains a certain word?

So if div1 contains the text 'TriggerWord', I want div 2 to become red. Below is my attempt. Thanks

     $("document").ready(function () {  
       if ($("#div1:contains('Tr开发者_StackOverflow社区iggerWord')")) {
          $('#div2').css('color','red');
       }
    });


Don't quote document. Other than that your attempt is correct. The :contains() selector is what you need:

$(document).ready(function() {  
    if ($('#div1:contains("TriggerWord")').length > 0) {
        $('#div2').css('color', 'red');
    }
});

or with the shorthand form:

$(function() {  
    if ($('#div1:contains("TriggerWord")').length > 0) {
        $('#div2').css('color', 'red');
    }
});

And here's a live demo.


$(document).ready(function () {
    if ($("#div1").html().indexOf('TriggerWord') >= 0) {
        $('#div2').css('color', 'red');
    }
});


Regex method:

$(function() {

    var reg = /Trigger/g;

    if($('#div1').text().match(reg)) {
        $('#div2').css({color: 'red'});
    }

});

Working fiddle: http://jsfiddle.net/each/NJ966/


$(function() {
    if (/triggerWord/.test($("div1").text()) {
        $("div2").css('color', 'red');
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜