tags:

views:

142

answers:

2
+1  Q: 

jQuery text match

I have an anchor tag with text and I want to check if the given var matches the string exactly.

This works, but I would like to use something other than contains, since it will match two elements if the contain the given string. I want it to match exactly.

Any ideas ?

function test(submenu){
$('a:contains("' + submenu + '")', 'ul.subMenu li').css('font-weight', 'bold');
}
+1  A: 

Is this what you're looking for:

function test(submenu)
{
   if ($("ul.submenu li a").text() == submenu)
   { 
      // do whatever here 
   }
}

However, I'm not sure what you mean by, "This works, but I would like to use something other than contains, since it will match two elements if the contain the given string. I want it to match exactly."

ryanulit
You probably want to replace `=` with `==`. ;)
Jordan Ryan Moore
if submenu = 'News' then it would match a link with text 'News' and 'Testing News', therefore applying the css to both.
gmcalab
or better yet: ===
cobbal
Corrected now, thanks jordan. @gmcalab, this code and the above (and better code) by womp will do exact matching.
ryanulit
+3  A: 

You can use the .filter() function instead of the :contains filter to apply a custom filter to your selector result set.

In this case apply a custom filter to look for text with an exact match. Something like:

$('a').filter( function (index) {
    return $(this).text() == submenu;
})
  .css('font-weight', 'bold');
womp
If boundary whitespace needs to be ignored just tweak as such: $.trim($(this).text()) == submenu
micahwittman