简体   繁体   中英

jquery How do I add a class to span within a dl based on the text it contains?

I want to be able to add the class="st_sharethis" to the menu link: Tell A Friend on this site http://www.easyspacedesign.com/fh/ConnectBell_/ . There is no way to add a specific class or id to a menu link in the cms we use so going to have to use jquery to do it.

So I will have to do it based on the text within the span tag that is within the a tag.

So far i have tried:

  $('.main_menu span:contains("Tell A Friend")').attr('class','st_sharethis');

  $('.main_menu span').each(function ()
  {
    if ($(this).text() == "Tell A Friend")
    $(this).attr('id','rev3');
  }

neither has worked.

If this menu item will always be latest one:

$('#menu dl dt:last a').addClass('myclass');

Also, you have specific class last on this menu item, so you can:

$('dt.last').addClass('myClass');

Or you can just test content of the link:

$('#menu dl dt a span:contains("Tell A Friend")').parent().addClass('myClass');

The following adds a class and id to the element.

$('.main_menu span:contains("Tell A Friend")')
    .addClass('st_sharethis')
    .attr('id', 'rev3');

Your code is fine, you just need to add a ");" at the end!

 $('.main_menu span:contains("Tell A Friend")').attr('class','st_sharethis');

   $('.main_menu span').each(function ()
   {
     if ($(this).text() == "Tell A Friend")
     $(this).attr('id','rev3');
   }
 );   // ADD this line !

But of course it would be better to just chain the commands:

 $('.main_menu span:contains("Tell A Friend")')
  .attr('class','st_sharethis')
  .attr('id','rev3');

This works fine for your markup:

$('#menu span:contains("Tell A Friend")')
           .addClass('st_sharethis')
           .attr('id','rev3');

Live example: http://jsfiddle.net/ydFFR/

如果是最后一个,请尝试

$('a.main_menu.last').find('span').addClass('st_sharethis');

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