Issue
I have a sidebar menu with anchor link. The idea is simple: Once someone clicks on a menu item, that specific item gets the "active" class and the previous "active" menu item gets that class removed.
Somehow the code doesn't work and I can't figure out why.
This is the page: https://www.otto-keller.de/wissenswertes/
function setActive(element){
var menuitems = document.querySelectorAll(".leftmenu_item.active");
[].forEach.call(menuitems, function(el) {
el.classList.remove("active");
});
element.classList.add("active");
}
.active {
color: red;
}
<ul>
<li class="leftmenu_item active" onclick="setActive(this)">
<a href="#daunenfedern">Daunen & Federn</a>
</li>
<li class="leftmenu_item " onclick="setActive(this)">
<a href="#inlett">Inlett</a>
</li>
<li class="leftmenu_item " onclick="setActive(this)">
<a href="#allergiker">Allergiker</a>
</li>
<li class="leftmenu_item " onclick="setActive(this)">
<a href="#waschmittel">Waschmittel</a>
</li>
</ul>
function setActive(element){
var menuitems = document.querySelectorAll(".leftmenu_item.active");
[].forEach.call(elems, function(el) {
el.classList.remove("active");
});
element.classList.add("active");
}
I tried to look first for the element that has the active class already to remove it. Then add the "active" class to the element which was clicked on with onclick().
Somehow it doesn't work on the live page, but does work in the editor.
Solution
Change this
[].forEach.call(elems, function(el) {
el.classList.remove("active");
});
To this
menuitems.forEach((element, index, entireList) => {
element.classList.remove("active");
});
Iterate over the NodeList returned by document.querySelectorAll()
instead of the []
like you did earlier. See the correct signature for the forEach
.
Answered By - Chukwujiobi Canon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.