简体   繁体   中英

jQuery: Add Class Active to <a> with current page href

I am looking for a way to add an active class to the tag that has an href of the current page.

Say I am on the page localhost:3000/inbox, I need my html to change add the correct class to the correct which are all located in the div with the class sidebar.

So when at "/inbox" jQuery should make my html look like this:

<div class="sidebar">
<a href="/link">
  <i class="fa fa-inbox"></i>
  <span>A Link</span>
</a>
<a class="active" href="/inbox">
  <i class="fa fa-inbox"></i>
  <span>Inbox</span>
</a>
</div>

This is what I tried, but it doesn't work, it breaks the code:

var href = $(location).attr('href');
  ('.sidebar').find('a[href*=href]').addClass("active");

Thank you. Please let me know if I wasn't clear enough.

It looks like you're almost doing it right, with the minor mistake of forgetting to call jQuery or $ . You also need to concatenate your selector, so that the value of href is searched for.

$('.sidebar').find('a[href*="' + href + '"]').addClass('active');

You probably also need to find just the path name to match your href values, like so:

var href = window.location.pathname;

How about this?

var path = window.location.pathname;
$(".sidebar a[href*='"+path+"']").addClass("active");

Please note the ' around the path. They are there because jQuery cause syntax error if there are unquoted / in the selector.

When I try it on JSFiddle, I get a / at the end of the path. You might want to add that to your links, or you can remove it from the path variable like this:

if(path.charAt(path.length-1) == "/")
    path = path.substring(0, path.length - 1);

Then some browsers might not include the leading / (or at least I think so), so you might want to add it in case it isn't already there:

if(path.charAt(0) != "/")
    path = "/" + path;

Since you use *= you might match more than the current page. For instance, if you are on /inbox/ you will also add the class to links to /inbox/sub/folder . To avoid this, use = instead.

Taken together, you would get this:

var path = window.location.pathname;
if(path.charAt(path.length-1) == "/")
    path = path.substring(0, path.length - 1);
if(path.charAt(0) != "/")
    path = "/" + path;
$(".sidebar a[href='"+path+"']").addClass("active");

Here is a working JSFiddle. (You might need to press run to make it work, as the URL is different the first time the page load.)

As far as I understand your question you want to change all divs that have a href of '/inbox' to have the class "active"

Your code should therefore look like this

$(document).ready(function(){

     $(.sidebar a[href=='/inbox']){

         $(a[href=='/inbox').addClass('active');

     }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM