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
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;
});
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With