There is a menu with two tabs that contain submenus. When clicking on a tab, two events should occur:

1) when clicking on an element, the .active class is added to this element, and the .active class should be removed for another element.

2) the active tab of the menu is visible. The second menu is hidden, has a class .hide . And accordingly, when you click on the corresponding tab, the menu becomes visible.

How to delete a class .active at an element when adding a class .active another element? And how to link the active tabs with the display of the hidden menu, i.e. remove class .hide ?

JS Code:

 document.addEventListener('DOMContentLoaded', function () { var wrapnavs = document.getElementById('js-navigation'), navs = wrapnavs.getElementsByTagName('div'); for( var i = 0; i < navs.length; i++ ){ navs[i].addEventListener('click', selectMenu); } function selectMenu() { if(this.classList.contains('active')){ this.classList.remove('active'); } else { this.classList.add('active'); } } console.log('get to the choppa!!!'); }); 

    1 answer 1

    I did this:

     'use strict'; document.addEventListener('DOMContentLoaded', function () { var navs = document.querySelectorAll('#js-navigation div'); for( var i = 0; i < navs.length; i++ ){ navs[i].addEventListener('click', selectMenu(i), false); } function selectMenu(iterator) { return function() { var parents = document.querySelectorAll('#js-navigation div'); parents.forEach(function(item, iter) { item.classList.remove('active'); if(iterator == iter) { item.classList.add('active'); } }); var topMenu = document.querySelectorAll('.ntk-top-menu'); topMenu.forEach(function(item, iter) { item.classList.add('hide'); if(iterator == iter) { item.classList.remove('hide'); } }); } } }); 

    UPD

    Updated code.

    • But can there be a case when there are several elements with a class active? - Grundy