Can anyone advice me why the allTabs forEach wont work when I am trying to add the .none
class
?
When clicking second item the other class should disappear but it doesn't,
let allTabs = document.querySelectorAll('.none');
function setActiveTab(tab) {
allTabs.forEach((tabs) => {
tabs.classList.add("none")
})
let singleTab = document.querySelector(`.${tab}`)
singleTab.classList.toggle("block")
}
.none {
display: none;
}
.block {
display: block;
}
<div>
<button onclick="setActiveTab('first')">
Test1
</button>
<button onclick="setActiveTab('second')">
Test2
</button>
</div>
<div class="none first">
first tab
</div>
<div class="none second">
second tab
</div>
A better approach is just to remove the none
class on the current tab. You won't need the block
class.
let allTabs = document.querySelectorAll('.none');
function setActiveTab(tab) {
allTabs.forEach((tabs) => {
tabs.classList.add("none")
})
let singleTab = document.querySelector(`.${tab}`)
singleTab.classList.remove("none")
}
.none {
display: none;
}
<div>
<button onclick="setActiveTab('first')">
Test1
</button>
<button onclick="setActiveTab('second')">
Test2
</button>
</div>
<div class="none first">
first tab
</div>
<div class="none second">
second tab
</div>
if you look at the inspector, the class none is always present.