how to loop through menu and remove class and then add class to current menu item
-
19-09-2019 - |
Question
I have this menu structure that is used to navigate through content slider panels.
<div id="menu">
<ul>
<li><a href="#1" class="cross-link highlight">Bliss Fine Foods</a></li>
<li><a href="#2" class="cross-link">Menus</a></li>
<li><a href="#3" class="cross-link">Wines</a></li>
<li><a href="#4" class="cross-link">News</a></li>
<li><a href="#5" class="cross-link">Contact Us</a></li>
</ul>
</div>
I would like to loop through these elements and remove the highlight class and then add the highlight class to the current / last clicked menu item.
Any ideas? Any help would be greatly appreciated.
Thanks
Jonathan
Solution
May be so?
$('#menu li a').click(function(){
$('#menu li a').removeClass('highlight');
$(this).addClass('highlight');
});
OTHER TIPS
...your <head> and opening <body> tags...
<div id="menu">
<ul>
<li><a href="#1" class="cross-link highlight">Bliss Fine Foods</a></li>
<li><a href="#2" class="cross-link">Menus</a></li>
<li><a href="#3" class="cross-link">Wines</a></li>
<li><a href="#4" class="cross-link">News</a></li>
<li><a href="#5" class="cross-link">Contact Us</a></li>
</ul>
</div>
<script type="text/javascript">
(function( $ ) {
$( "#menu ul li a" ).click( function() {
$( this ).parent().parent().filter( 'a' ).removeClass( 'highlight' );
$( this ).addClass( 'highlight' );
});
})( jQuery );
</script>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow