I wrote bunch of codes which expands my accordion but here is a problem. When I click on button to expand accordion body, my listener calls twice.
Did anyone face this problem?
const accordionToggler = document.querySelectorAll('.accordion-toggler');
// expanding accordion by clicking on a single accordion toggler
accordionToggler.forEach(toggler => {
toggler.addEventListener('click', (e) => {
const caret = toggler.querySelector('.chevron-caret'); // chevron ico
if (caret.classList.contains('rotate')) {
caret.classList.remove('rotate')
} else {
caret.classList.add('rotate')
}
if (e.currentTarget.nextElementSibling.style.maxHeight === '' || e.currentTarget.nextElementSibling.style.maxHeight === '0px') {
e.currentTarget.nextElementSibling.style.maxHeight = toggler.nextElementSibling.scrollHeight + 'px';
} else {
e.currentTarget.nextElementSibling.style.maxHeight = 0;
}
console.log('menu loop function click');
});
console.log('menu loop function');
});
// expanding accordion by clicking on a single accordion toggler

You did not supply an example of your HTML, but I'm guessing your problem is that you have nested .accordion-toggler.
clicking one of them means you clicked all of its parents.
This has to do with event bubbling and capturing phases.
When you add an event listener you can control the phase of capturing this event. controlled by addEventListener third argument.
What you need is to use the event.stopPropagation inside your listener. You can read more about it here.
If you'll update your question with a complete code (and DOM) example then I'll be able to update my answer to be more accurate to your specific issue.
Another solution for your situation can be attaching only one event listener to the root of the accordion and then responding according to the targe. You can further read about currentTarget which you might also need in your case if you do want the parents to respond.
Here is a code example for that:
const rootAccordionToggler = document.querySelector('.parentOfAll > .accordion-toggler');
rootAccordionToggler.addEventListener('click', (e) => {
const target = e.target;
const caret = target.querySelector('.chevron-caret'); // chevron icon
caret.classList.toggle('rotate');
if (target.nextElementSibling.style.maxHeight === '' || target.nextElementSibling.style.maxHeight === '0px') {
target.nextElementSibling.style.maxHeight = target.nextElementSibling.scrollHeight + 'px';
} else {
target.nextElementSibling.style.maxHeight = 0;
}
});