addClass if contains match
HTML:
<li class="widgetcontainer widget_text" id="text-3">
<h3 class="widgettitle">Static Ad</h3>
<div class="textwidget"><img alt="" src="static/announcement.png"></div>
</li>
jQuery:
if( $('.widget_text')[0] ) {
$('.widgettitle').each(function() {
if ( $(this).containts('Static Ad') ) {
$(this).parent().addClass('myclass');
}
});
}
... isn't working. Neither:
if( $('.widget_text')[0] ) {
$('.widget_text').each(function() {
if ( $(this).childr开发者_JAVA技巧en('h3:contains:("Static Ad")') ) {
$(this).parent().addClass('static-ad');
}
});
}
How do I fix?
Thanks!
You have a typo: if ( $(this).contains('Static Ad') ) {
Try:
$('.widgettitle:contains("Static Ad")').parent().addClass('myclass');
or
$('.widget_text').each(function() {
if ( $(this).children('h3:contains("Static Ad")').length > 0 ) {
$(this).addClass('static-ad');
}
})
You have an additional colon :
in your code (remove it) and I think you have to remove parent()
.
Besides that, there is no need to test for $('.widget_text')[0]
. If there is no element with class widget_text
, $('.widget_text').each()
won't do anything anyway ;)
$('.widgettitle:contains("Static Ad")').parent().addClass('myclass');
Read more here:
http://api.jquery.com/contains-selector/
A demo here:
http://jsbin.com/alega3/2
jQuery.contains
is to test if one DOM node is within another DOM node.
Try this instead:
$('.widget_text').filter(function() {
return $(this).find('.widgettitle').text().indexOf('Static Ad') > -1;
}).addClass('myclass');
This will select all elements with widget_text class, filter out those that do not have a descendant with widgettitle class with “Static Ad” in its text, and add myclass to it.
精彩评论