I want to add a class to a element when there a keyword is found matched in that ‘s href
html,
<ul class="menu-header">
<li><a href="http://localhost/website/#/home/" class="button-header current">HOME</a></li>
<li><a href="http://localhost/website/#/gallery/" class="button-header">GALLERY</a></li>
<li><a href="http://localhost/website/#/people/" class="button-header">PEOPLE</a></li>
<li><a href="http://localhost/website/#/contact/" class="button-header">Contact</a></li>
</ul>
so if the keyword is “gallery”, then “current” should be added to that element and the “current” class in other elements must be removed.
jquery,
var request = "gallery";
// Add the class to the menu.
$(".menu-header li").each(function(){
var object = $(this); // which is <li>
var siblings = object.siblings(); // other <li>s
// Clean all siblings' style.
siblings.find("a").removeClass('current');
var array_link = $("a",this).attr("href").split('/');
if ($.inArray(request, array_link) == 1) $("a.button-header",object).addClass("current");
});
I managed to remove “current” class from all elements, but not able to add the “current” class.
Any ideas what I have missed?
You don’t need to loop through them all yourself to accomplish this:
Remove the current class from any
li athat has it, then add it to theli athat has an href that matchesgallery. Here it is again with a variable: