0

I have an svg icon that on click, I want it to rotate 180 degrees. Currently, only the first icon toggles the class, but I'm trying to get all icons to toggle.

I'm not sure what I'm missing...

let accordionChevron = document.querySelector('.rotate');

accordionChevron.addEventListener('click', function() {
  this.classList.toggle('down');
})
.rotate {
  transition: all 0.2s ease-in-out;
}
.rotate.down {
  transform: rotate(180deg);
}
<svg class="rotate" fill="none" height="11" viewBox="0 0 16 11" width="16" xmlns="http://www.w3.org/2000/svg">
  <path d="m0 2.82837 2-2 6 6 6-6 2 2-8 8.00003z" fill="#000a70"></path>
</svg>
<hr>
<svg class="rotate" fill="none" height="11" viewBox="0 0 16 11" width="16" xmlns="http://www.w3.org/2000/svg">
  <path d="m0 2.82837 2-2 6 6 6-6 2 2-8 8.00003z" fill="#000a70"></path>
</svg>
Millhorn
  • 2,953
  • 7
  • 39
  • 77
  • Use [event delegation](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple event listeners — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](//developer.mozilla.org/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). – Sebastian Simon Aug 18 '21 at 01:07
  • [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+event+listener+for+all+elements+with+class) of [Want to add “addEventListener” on multiple elements with same class](/q/51573435/4642212). – Sebastian Simon Aug 18 '21 at 01:10
  • I did not see that question. Thank you! – Millhorn Aug 18 '21 at 01:12

1 Answers1

0

You may try the following:

let accordionChevronList = document.querySelectorAll('.rotate');
accordionChevronList.forEach(accordionChevron=>{
    accordionChevron.addEventListener('click', function() {
        this.classList.toggle('down');
    });
});
The KNVB
  • 3,588
  • 3
  • 29
  • 54