Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
Toogle active class using getElementById

I am trying to change class from none to active using document.getElementById but it is just adding active not removing it.

page.html

function toggleIt() {
  let collapseModel = document.getElementById(`collap_id`).className += "content active";
  collapseModel[0].classList.toggle("active")
}
.content {
  padding: 10px 20px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;
}

.content.active {
  padding: 10px 20px;
  display: block;
  overflow: hidden;
  background-color: #f1f1f1;
}
<button onclick="toggleIt();">Open</button>

<div class="content" id="collap_id">
  Here will be all the details
</div>

When I click on toggle it then it is opening but not closing , it is also showing "Uncaught TypeError: Cannot read properties of undefined (reading 'toggle')"

I have tried many times but it is not toggling.

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

0

1) getElementById will give you single HTML element so no need to use index.

2) You just have to toggle it using toggle method

function toggleIt() {
  let collapseModel = document.getElementById(`collap_id`);
  collapseModel.classList.toggle("active")
}

function toggleIt() {
  let collapseModel = document.getElementById(`collap_id`);
  collapseModel.classList.toggle("active")
}
.content {
  padding: 10px 20px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;
}

.content.active {
  padding: 10px 20px;
  display: block;
  overflow: hidden;
  background-color: #f1f1f1;
}
<button onclick="toggleIt();">Open</button>

<div class="content" id="collap_id">
  Here will be all the details
</div>

about 4 years ago · Juan Pablo Isaza Report

0

Here is my proposition with using querySelector and addEventListener.

const btn = document.querySelector(".btn");
const msg = document.querySelector(".content");

btn.addEventListener("click", () => {
  msg.classList.toggle("active");
});
.content {
  display: none;
}

.active {
  padding: 10px 20px;
  display: block;
  overflow: hidden;
  background-color: #f1f1f1;
}
<button class="btn">
  open
</button>

<div class="content" id="collap_id">
  Using querySelector and addEventListener.
</div>

about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!