Cameron
Cameron

Reputation: 28843

jQuery find link that matches current page

I have the following code that is trying to find a link that matches the current url: $item = $('ul#ui-ajax-tabs li a').attr('href', $(location).attr('pathname')); but instead it changes all the links to the current url :P

Can anyone help me fix it. Cheers

Upvotes: 6

Views: 10854

Answers (3)

Stephan Ahlf
Stephan Ahlf

Reputation: 3497

Where URL format might change in Production like ASP.NET :/ this might work better if you ignore the end slash of URLs.

$('.mdl-navigation').find("a").filter(function () {
  return this.href.replace(/\/+$/, '') === window.location.href.replace(/\/+$/, '');
}).addClass('current-active-page-url');

Upvotes: 1

Rob W
Rob W

Reputation: 349082

Use this query. Your code changes all href attributes of the selected links, rather than returning a selection of links with a matching href attribute:

$("a[href*='" + location.pathname + "']")

The [href*=..] selector returns a list of elements whose href attribute contains the current pathname.

Another method, return all elements whose href contains the current pathname. prop() is used instead of attr(), so that relative URLs are also correctly interpreted.

$item = $('ul#ui-ajax-tabs li a').filter(function(){
    return $(this).prop('href').indexOf(location.pathname) != -1;
});

Upvotes: 16

Luca Matteis
Luca Matteis

Reputation: 29267

That's because your CSS selector ul#ui-ajax-tabs li a matches more than one thing. Try being more specific with your selector, such as ul#ui-ajax-tabs li:first-child a.

Upvotes: 0

Related Questions