Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Accordion

josephweiss2
josephweiss2
6,982 Points

Better solution!

In the JavaScript code after passing forEach it would be even better if we put in an IF statement, like this only if you press on the header that has the + or - on it the content gets hidden or active and not if you press it everywhere on the .accordion div. I have included here my if statement: Look much nicer in my opinion!

const accordions = document.querySelectorAll('.accordion');
accordions.forEach(accordion => {
  accordion.addEventListener('click', e => {

    if (e.target.classList.contains('accordion-header') || e.target.nodeName=='BUTTON') {

      let accordionBtn = accordion.querySelector('button');
      accordion.classList.toggle('active');
      if (accordionBtn.textContent=== '+') {
        accordionBtn.textContent= '-'
      } else {
        accordionBtn.textContent= '+'
      }

    }

  })
});
Dustin U
seal-mask
.a{fill-rule:evenodd;}techdegree
Dustin U
Treehouse Teacher

Hey there Joseph 👋🏼 I love this level of detail, great work here!