From what you've described I'd suggest:
$('.main-navbar a').addClass(function(){
// caching for future use:
var that = this,
// retrieving the pathname, and splitting it on the '/' characters
// to form an array (for easier removals later):
path = that.pathname.split('/'),
// so we're only retrieving this once per iteration over the collection:
winPath = window.location.pathname;
// 'len' (the number of iterations) is 'path.length - 1' because if
// we remove the last element from the array, they will *all* match:
for (var i = 0, len = path.length - 1; i < len; i++){
// testing to see if there's a match at the start of the pathname:
if (winPath.indexOf(path.join('/')) === 0) {
// this is entirely unnecessary, and serves only to show
// (in the demo) what was matched:
$(this).text(function(_,oldText){
return oldText + ' (found match at: ' + that.hostname + path.join('/') + ')';
});
// if the pathname, or the truncated pathname, matches we add the
// 'selected' class-name to the element:
return 'selected';
}
else {
// otherwise we remove the last element of the array, and try again:
path.pop();
}
}
});
Truncated JS Fiddle demo (removed the call to text()
).
Edited to add the 'selected'
class-name to the li
ancestor, and to address the need to match the subdomains:
$('.main-navbar a').addClass(function(){
var that = this,
path = that.pathname.split('/'),
// retrieves the hostname, including the subdomain,
// eg: 'subdomain.domain.tld' from the link.
pathHost = that.hostname,
winPath = window.location.pathname,
// as above, but for the window.location:
winHost = window.location.hostname;
// if the hostname from the path is exactly equal ('===') to
// that from the window.location then we test the pathname:
if (winHost === pathHost) {
for (var i = 0, len = path.length - 1; i < len; i++){
if (winPath.indexOf(path.join('/')) === 0) {
$(that).closest('li').addClass('selected');
}
else {
path.pop();
}
}
}
});
References:
- jQuery:
- JavaScript: