it is fairly simple.
I want to make a current class and put it on a link that is currently active
like this : <li class="li current"><a>Link1</a></li>
but before that, the JS should get all of element with class="li", loop through it and remove the class=" current" if any.
after looping end, then add class=" current" to the element which triggers the event.
for example if user clicks on link3 then JS should remove the class=" current" on link1 and then add class=" current" on link3
it would look like this : <li class="li current"><a>link3</a></li>
it looks like I cannot use getElementsByClassName() for event listener. what should I do to make an event listener then?
the HTML
document.addEventListener("DOMContentLoaded",function(){
var et = document.getElementsByClassName("li");
for(i=0; i <et.length; i++){
et[i].addEventListener("click",function(){
funclink(event);
});
};
});
function funclink(event){
//first get all element with class "li" and remove class " current"
//then add class " current" to the element which triggers the event
var slink = document.getElementsByClassName("li");
for(i =0; i < slink.length; i++){
slink[i].className = slink[i].className.replace(" current","");
}
event.currentTarget.className += " current";
}
.current {
color : orange;
}
<ul id="navmenu">
<li class="li current"><a href="#">Home</a></li>
<li class="li"><a href="#">Call Service</a>
<li class="li"><a class="a-left" href="#">Rental</a></li>
<li class="li"><a class="a-left" href="#">Sales</a></li>
</li>
</ul>