最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - addClass if contains match - Stack Overflow

programmeradmin0浏览0评论

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).children('h3:contains:("Static Ad")') ) {
        $(this).parent().addClass('static-ad');
      }
    }); 
}

How do I fix?

Thanks!

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).children('h3:contains:("Static Ad")') ) {
        $(this).parent().addClass('static-ad');
      }
    }); 
}

How do I fix?

Thanks!

Share Improve this question edited Feb 13, 2010 at 13:00 eozzy asked Feb 13, 2010 at 12:51 eozzyeozzy 68.9k109 gold badges285 silver badges447 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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./contains-selector/

A demo here:

http://jsbin./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.

发布评论

评论列表(0)

  1. 暂无评论