简体   繁体   中英

How to add specific class to anchor tag has href equal to URL using jquery?

I want to have a jQuery dynamic menu that navigates to the <a></a> tags and the one that include with the page URL.

 $('ul.nav.navbar-nav.side-nav.nicescroll-bar li').find('a').each(function() { var text = $(this).attr("href"); if (window.location.href.includes(text)) { $('ul.nav.navbar-nav.side-nav.nicescroll-bar li a').addClass('active') } else {} });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="nav navbar-nav side-nav nicescroll-bar" style="overflow: hidden; width: auto; height: 100%;"> <li><a href="home">home</a></li> <li><a href="dashboard">dashboard</a></li> <li><a href="base">base</a></li> <li><a href="test">test</a></li> </ul>

In this code, there is a color change in all menus, which should change the color of the menu according to the page's address.

Just remove the class in else:

if (window.location.href.includes(text)) {
  $(this).addClass('active')
} else {
  $(this).removeClass('active')
}

Change

if (window.location.href.includes(text)) {
  $('ul.nav.navbar-nav.side-nav.nicescroll-bar li a').addClass('active')
}

into

if (window.location.href.includes(text)) {
  $(this).addClass('active')
}

It works when you use this to add the class. I changed one href to stack because the href of the snippet is something like stacksnippet. For that element it colors red.

 $('ul.nav.navbar-nav.side-nav.nicescroll-bar li').find('a').each(function() { var text = $(this).attr("href"); if (window.location.href.includes(text)) { $(this).addClass('active') } });
 .active { color: red; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="nav navbar-nav side-nav nicescroll-bar" style="overflow: hidden; width: auto; height: 100%;"> <li><a href="home">home</a></li> <li><a href="dashboard">dashboard</a></li> <li><a href="stack">base</a></li> <li><a href="test">test</a></li> </ul>

You can simplify your selector and code and use .filter() instead of .each()

$('ul.navbar-nav li a').filter(function(){
  return window.location.href.includes($(this).attr('href'));
}).addClass('active');

 window.location.href = "#home"; $('ul.navbar-nav li a').filter(function(){ return window.location.href.includes($(this).attr('href')); }).addClass('active');
 .active {color:red}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="nav navbar-nav side-nav nicescroll-bar" style="overflow: hidden; width: auto; height: 100%;"> <li><a href="home">home</a></li> <li><a href="dashboard">dashboard</a></li> <li><a href="base">base</a></li> <li><a href="test">test</a></li> </ul>

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