Tell me how to make the switching of the class active to the element that was clicked, and where before it was the class active was deleted. Found a working code:

<div class="main-nav"> <a href="#" class="active">1</a> <a href="#">2</a> </div> var href=$(".main-nav a"); href.click(function () { var scrollId = $(this).attr("href"); change_active($(this)); //scroll_if_anchor(scrollId); return false; }); function change_active(current) { console.log(href); href.removeClass("active"); current.addClass("active"); } 

However, I need it to be not links, but li elements:

 <ul class="main-nav"> <li class="active">1</li> <li>2</li> </ul> 

    1 answer 1

    This should help

     $('.main-nav li').on('click',function(){ $('.main-nav li').removeClass('active'); $(this).addClass('active'); }); 
     .active{ background:green; color:#fff; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="main-nav"> <li class="active">1</li> <li>2</li> <li>3</li> <li>4</li> </ul> 

    • It works as it should, thank you so much! - alex-lenk