I can not highlight the selected menu. Here is my code:

jQuery(document).ready(function($) { $('.nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('current-menu-item'); }); 
 #nav > li span { padding-right: 15px; } #nav > li:hover, #nav > li.current-menu-item, #nav > li.current_page_item { background: url(/wp-content/themes/new/img/current-menu-item.png) no-repeat 0px -37px; } #nav > li:hover span, #nav > li.current-menu-item span, #nav > li.current_page_item span { display: block; background: url(/wp-content/themes/new/img/current-menu-item.png) no-repeat top right; } #nav > li:hover a, #nav > li.current-menu-item a, #nav > li.current_page_item a { color: #fff; text-shadow: 0px 2px 0 rgba(0, 0, 0, 0.3); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="nav" class="sf-menu"> <li><a href="/"><span>Главная</span></a> </li> <li><a href="best-story"><span>Проекты</span></a> </li> <li><a href="about"><span>О нас</span></a> </li> <li><a href="share-story"><span>Контакты </span></a> </li> </ul> 

Help me find a bug, thanks!

  • one
    Is your menu duplicated on every page where links go or are you putting up a template? Or the link you insert a piece in the same document? Help a little help you! - Kirill Korushkin
  • one
    sample searches by class, and assigned ID - webDev_

1 answer 1

In the HTML task, CSS and jQuery do not match:
1. jQuery is looking for a class .nav , but should search by IDI #nav
2. jQuery adds a class to element a , and styles are written for li

You can fix, for example, like this:

 jQuery(document).ready(function($) { $('#nav a[href^="/' + location.pathname.split("/")[1] + '"]').parent().addClass('current-menu-item'); });