Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find link that matches current page

Tags:

jquery

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

like image 462
Cameron Avatar asked Oct 13 '11 09:10

Cameron


2 Answers

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;
});
like image 56
Rob W Avatar answered Nov 24 '22 07:11

Rob W


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');
like image 27
Stephan Ahlf Avatar answered Nov 24 '22 08:11

Stephan Ahlf