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');
}
});
精彩评论