document.getElementById('panel-one').onclick = function() {
document.getElementById('panel-one').classList.toggle('active');
if(document.getElementById('panel-one').classList.contains('active')){
document.getElementById('panel-one').classList.add('changing-icon');
} else {
document.getElementById('panel-one').classList.remove('changing-icon');
}
}
document.getElementById('panel-two').onclick = function() {
document.getElementById('panel-two').classList.toggle('active');
if(document.getElementById('panel-two').classList.contains('active')){
document.getElementById('panel-two').classList.add('changing-icon');
} else {
document.getElementById('panel-two').classList.remove('changing-icon');
}
}
const panels = document.getElementsByClassName("panel");
const i;
for (i = 0; i < panels.length; i++) {
panels[i].addEventListener("click", function() {
// тут ещё можно поставить удаление у всех акордионов класса 'active', если необходимо
this.classList.toggle("active");
const panel = this.nextElementSibling;
if(this.classList.contains('active')){
this.classList.add('changing-icon');
} else {
this.classList.remove('changing-icon');
}
if (panel.style.maxHeight) {
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
});
}
<button class="panel">Аккордеон 1</button>
<div class="panel-body">
<p>текст аккордеона</p>
</div>
document.addEventListener(
'click',
(e) => {
// const classes = e.target.classList;
const classes = e.target.closest('.panel')?.classList;
if (!classes?.contains('panel')) {
return;
}
classes.toggle('active');
classes.toggle('changing-icon', classes.contains('active'));
}
);