views:

162

answers:

6

I am using accordion menu on an e-commerce site. The menu stays open with the options until the product page. On that page I am trying to use the breadcrumbs to match text in the menu and then apply a class to open the menu to the correct category for the page.

Here is my code:

$(document).ready(function(){
 var bctext = $('#ProductBreadcrumb ul li:last-child').prev('li').children().text();
$('ul#accordion a:contains(bctext)').parent().parent().addClass('special');

 });

The variable returns the correct text, and if I put a matching string ("Tomato Sauces") in the :contains it works just like I want it to and applies the class. However when I use bctext variable it wont work.

I also tried a:contains($(bctext)) and it didn't work. Is it my syntax?

Thanks

+3  A: 

Try:

$('ul#accordion a:contains(' + bctext + ')')
Crescent Fresh
thanks, i didnt think of that one :-)
+1  A: 

Change:

$('ul#accordion a:contains(bctext)').parent().parent().addClass('special');

to:

$('ul#accordion a:contains(' + bctext + ')').parent().parent().addClass('special');

The first way, the way you had it, is telling JavaScript to use the string 'bctext' as the contains parameter. What you actually want is the string which is contained within the bctext variable. Therefore you have to use it outside of the quotes and use concatenation to create your selector string.

Phairoh
thanks, i was confused because i thought if it wasnt in quotes it would know it was a variable...still learning...
A: 

This line should be:

$('ul#accordion a:contains(' + bctext + ')').parent().parent().addClass('special');
Tim S. Van Haren
+2  A: 

You could use Traversing/contains also:

$('ul#accordion a').contains(bctext);
CMS
I like this way best, I always avoid string concatenations within a query if I can. It's more secure, clear, and just seems cleaner
cobbal
`$.fn.contains()` was deprecated in 1.2 and replaced with the filter expression in 1.3. See http://docs.jquery.com/Release:jQuery_1.2#Removed_Functionality
Crescent Fresh
@cobbal - I'm curious, what's more secure with this method compared to selector string concatenation?
Russ Cam
A: 

This is a special-character-save version, that uses filter instead of the deprecated contains method.

$('ul#accordion a').filter(function () { return $(this).text() == bctext; })

naltatis
A: 
$('ul#accordion a').filter(':contains(' + bctext + ')'  

is now preferred to the deprecated

$('ul#accordion a').contains(bctext); 

(as commented by Crescent Fresh)

pelms