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