• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

251
Views
Trying to add class to div element, but wont work

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>

about 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 3 years ago · Juan Pablo Isaza Report

0

if you look at the inspector, the class none is always present.

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error