Home > Blockchain >  Toogle active class using getElementById
Toogle active class using getElementById

Time:12-13

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  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.

CodePudding user response:

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  id="collap_id">
  Here will be all the details
</div>

CodePudding user response:

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 >
  open
</button>

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

  • Related