accordion

Javascript Accordion assign classes click event


Currently the class "open" is assigned to the "accordion_container" when it is clicked. So far everything is good. What I want to change is just that this happens when clicking on the "accordion_title" class. Thanks for your help, I'm a beginner in JS :)

let leistungen_container = document.querySelectorAll(".accordion_container");

leistungen_container.forEach((leistungen_container) => {
  leistungen_container.addEventListener("click", (event) => {
    const open = document.querySelector(".accordion_container.open");

    if (open && open !== leistungen_container) {
      open.classList.toggle("open");
    }
    leistungen_container.classList.toggle("open");
  });
});
.accordion_container {
  background: green;
}
.accordion_container.open {
  background: pink;
}
.accordion_title.open {
  background-color: yellow;
}
<div class="accordion_container">
  <div class="accordion_title">
    <p>Corporate Title</p>
  </div>
  <div class="accordion_content">
    <p>Corporate Content</p>
  </div>
</div>

<div class="accordion_container">
  <div class="accordion_title">
    <p class="textmonster">Websites</p>
  </div>
  <div class="accordion_content">
    <p>Websites Content</p>

  </div>
</div>

<div class="accordion_container">
  <div class="accordion_title">
    <p class="textmonster">SEO &amp; SEA</p>
  </div>
  <div class="accordion_content">
    <p class="textmonster">SEO Content</p>
  </div>
</div>


Solution

  • You can select the title when you add the event listener like this :

    let leistungen_container = document.querySelectorAll(".accordion_container");
    
    leistungen_container.forEach((leistungen_container) => {
      leistungen_container.querySelector(".accordion_title").addEventListener("click", (event) => {
    const open = document.querySelector(".accordion_container.open");
    
      if (open && open !== leistungen_container) {
        open.classList.toggle("open");
      }
    
      leistungen_container.classList.toggle("open");
     });
    });