Uncaught Error: Syntax error, unrecognized expression

Hi,

I’d like to update my navigation styles on page load by adding classes grabbed from the URL path. However, my code is throwing an error which I can’t work out.

My URL looks like this as I’m loading pages via ajax.

Im creating an array using the following:

var hashpath = window.location.hash.substring(1).split( '/' );

Then I’m using jQuery.each to loop through the array and add a class:


jQuery.each(hashpath, function(i, val) {
               urlclass = val.toString(); // tried converting to string just in case
               // alert(urlclass);
               // var className = "articles"; // if I use this in the selector below the class is add Ok.
                $('#menu-main li.' + urlclass + ' a').addClass('current');

            });

I would expect the element with the selector ‘a.articles’ to have the class ‘current’ added.
However, this is throwing an error as if it can’t see the variable passed in:

Uncaught Error: Syntax error, unrecognized expression: #menu-main li. a

Any pointers would be greatly appreciated.

Hi there,

Could you post a link to a page where I can see this not working.

Thanks for replying Pullo.

I not at my computer now and it was on my localhost.
I will see if I’m able to upload something later.

Cool!
It shouldn’t be too hard to sort out.
I’m turning in now and I have to work tomorrow, but I’ll be back online in the afternoon.

Well that helped! I stripped down the page and it focused my mind on what was happening.

I think it was that the ‘/’ on the beginning of the url (although there is one on the end too) that was stored as an empty variable which was running first and throwing and error.

So I added a check within the loop…

if (val === '') {
				  // ..
				  //alert("empty");
				} else {
					$('#menu-main-navigation > li.' + val + ' > a').addClass('current');
				}

This seems to have fixed it on my test page. Hopefully it will translate to the actual one.

Thanks!

Good news!
It is amazing how making a bare-bones example that others can reproduce can focus your mind on the task in hand and more often than not lead to you solving your own problem.