views:

1982

answers:

4

In jQuery, how do you select the <a> which href is pointing to the current URL

For example:
URL = http://server/dir/script.aspx?id=1

I want to select this <a>
<a href="/dir/script.aspx">...</a>

I tried this but it doesn't work:

var url = window.location.href;
$('#ulTopMenu a["'+url+'"*=href]').addClass("selected");

Probably wrong syntax. Anyone know the right way of doing it?

Thanks in advance

A: 

I do not know the answer to your question but is that selector syntax valid?

'#ulTopMenu a["http://www.foo.com"*=href]'

I'd imagine if such a thing is possible it'd be written as

'#ulTopMenu a[href*="http://www.foo.com"]'
Danny
A: 

Yeah I don't think it's valid... but

'#ulTopMenu a[href*="http://www.foo.com"]'

is valid but it means href contains that url

What I want is the url contains the href

+3  A: 

It sounds like you're trying to solve the selected tab 'pattern'. I've found I can solve this myself with the following code:

var nav = location.pathname.substr(1).split('/', 2)[0] || '/';
if (nav) {
    $('#ulTopMenu a[href$="' + nav + '"]').parent().addClass('selected');
}

This basically says add the class of selected if the URL ends with the same ending as the current URL. Though you have to watch out for 'similar' urls - but if you have a lot of urls that are actually similar, you should probably consider a server side solution.

(I posted an article a while back on this technique - if it's actually what you're trying to do: http://leftlogic.com/lounge/articles/auto-selecting_navigation/)

Remy Sharp
A: 

Thanks Remy, it didn't really work but it's close.
Here is my final code

  var scriptname = GetUrlScriptname();
  $('#ulTopMenu a[href$="' + scriptname + '"]').parent().addClass('selected');

function GetUrlScriptname()
{
  var rex = new RegExp("\\/[^\\/]+\\.\\w+($|\\?)");
  var match = rex.exec(location.pathname);
  return match[0].substring(1);
}