简体   繁体   中英

Add active class to a href

I have a small issue with this code,

jQuery('.nav-menu  li:has(a[href="'+ window.location.pathname +'"])').addClass('active');

It gives me results like this:

<li class="active">
  <a href="/someUrl">Test</a>
 </li>

But I want something like this:

 <li>
  <a href="/someUrl" class="active">Test</a>
 </li>

Can somebody help me with this?

You are almost there. You need to find anchor tag before addClass .

jQuery('.nav-menu li:has(a[href="'+ window.location.pathname +'"])').find('a').addClass('active');

Add a tag after li in your selector.

jQuery('.nav-menu  li:has(a[href="'+ window.location.pathname +'"]) a').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