Auto adding .active class to menu

Auto adding .active class to menu

Hi guys,

I'm still new to jQuery, but with your help I can get things working :D
Now, I'm stuggeling with this:

I'm trying to add .active class to a menu, based on the URI.
It works with URL's like: /, /products, /about, /contact but not anymore when you go to /products/some-product.

I know what's wrong, but I can't find a working solution. I've tried a regex, but that didn't work either...
Thx in advance!

The code:
  1.             $(function() {               
                    var path = location.pathname;
               
                    if (path) {
                        $('#topmenu ul li a[href$="' + path + '"]').attr('class', 'selected');
                    }
                 });