patnz
patnz

Reputation: 1141

Adding variables to jquery selectors

How can I add variables into my selectors :

function addCurrentClass(){
    var loc = window.location;
    $('#nav li a[href = "' + loc + '"]').addClass('currentpage');
}

I've tried many variations of the above using different types of selectors and can't get it to change to the value contained in var loc.

Any ideas?

Thanks

Upvotes: 0

Views: 304

Answers (2)

Guffa
Guffa

Reputation: 700232

You should use window.location.href rather than window.location to get the url, however the main problem with the approach is probably that it only works if you have fully qualified URLs in your link tags. Local or relative URLs won't work.

Upvotes: 2

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

How about this -

function addCurrentClass(){
    var loc = window.location.toString();
    $('#nav li a[href = "' + loc + '"]').addClass('currentpage');
}

I think you need to convert the location into string before you can get the string URL. Details are here.

Upvotes: 0

Related Questions