How can I add .active to .accordion-item when I click to .accordion-item-header? I want to add .active to switch my bgc with javascript without jquery.
HTML
<div >
<div >
<div >Basics</div>
<div >
<div >
Lorem Ipsum
</div>
</div>
</div>
<div >
<div >Standard</div>
<div >
<div >
Lorem Ipsum
</div>
</div>
</div>
<div >
<div >Pro care</div>
<div >
<div >
Lorem Ipsum
</div>
</div>
</div>
</div>
CSS (SCSS)
.accordion {
border: 1px solid #E3E1D5;
border-radius: 20px;
padding: 40px 40px 30px 40px;
height: 100%;
&-item {
width: 250px;
padding: 14px 40px;
background: #EDF2EC;
border-radius: 20px;
&:not(:first-child) {
margin-top: 32px;
}
// &.active {
// background: #D6E7D2;
// }
&-header {
position: relative;
font-family: 'Inter';
font-weight: 700;
font-size: 20px;
color: #000000;
cursor: pointer;
&::after {
content: url('../icons/arrows/prices_arrow.svg');
position: absolute;
right: 0;
transition: all 0.6s;
}
&.active {
&::after {
content: url('../icons/arrows/prices_arrow.svg');
transform: rotate(-180deg);
}
}
}
&-body {
max-height: 0;
overflow: hidden;
transition: all 0.6s;
&.active {
max-height: 400px;
}
&-content {
margin-top: 12px;
border-top: 0.5px solid #AEA1A1;
}
}
}
}
JS
document.querySelectorAll('.accordion-item-header').forEach((accordionItemHeader) => { //получаю все header на которые буду нажимать
accordionItemHeader.addEventListener('click', () => {
accordionItemHeader.classList.toggle('active'); //добавляю класс активности для header <-> -
const accordionItemBody = accordionItemHeader.nextElementSibling; //получаю следующий элемент за header
if(accordionItemHeader.classList.contains('active')) {
//если у header есть класс активности, тогда выставляем max-height
accordionItemBody.style.maxHeight = accordionItemBody.scrollHeight 'px';
}
else {
accordionItemBody.style.maxHeight = 0;
}
});
});
enter image description here I want to add this class to accordion-item when I click on accordion-item-header. I do not know, how I can get accordion-item. I tried querySelector and in this case I change bgc only on first class even when I click on the second or third element, the bgc changes only for the first. I tried to use querySelectorAll but in this case I change my bgc for all element even the ones I didn't click on.
&.active {
background: #D6E7D2;
}
CodePudding user response:
document.querySelectorAll('.accordion-item-header').forEach((accordionItemHeader) => { //получаю все header на которые буду нажимать
accordionItemHeader.addEventListener('click', (evt) => {
console.log(evt.target);
const elai = evt.target.closest('.accordion-item');
console.log(elai);
elai.classList.toggle('active'); //добавляю класс активности для header <-> -
});
});
in your eventlistener just add 'event' (evt)
from this evt.target element clicked, you search 'closest' accordion-item
and you toggle your class