Home > Back-end >  Having difficulties toggling a class to .active (for a simple accordion style faq)
Having difficulties toggling a class to .active (for a simple accordion style faq)

Time:10-04

I'm trying to toggle the .accordionQuestions div to active once the btn element is clicked:

The hidden .accordionAnswers div is set to display: none on my stylesheet.

Once .accordionQuestions is active, .accordionAnswers is set to display: block.

I've tried looping over the .btn using addEventListener, but no luck so far.

I've tried using parentNode to access .accordionQuestion, and set that to active, but it doesn't seem to work. Any advice is greatly appreciated, thank you for your time!

I'm guessing that the .accordionQuestions.active can't access another div .accordionAnswers, even though it's in the same div. Os there any other way using toggle?

const btns = document.querySelectorAll('.btn')

btns.forEach(btn => {
  btn.addEventListener('click', () => {
    btn.parentNode.classList.toggle('active')
  })
});
.accordionAnswers {
  display: none;
}

.accordionQuestions.active .accordionAnswers {
  display: block;
}
<div >
  <div >
    <h3>How many team members can I invite?</h3>
    <button ><img src="images/icon-arrow-down.svg"/></button>
  </div>
  <div >
    <p>
      You can invite up to 2 additional users on the Free plan. There is no limit on team members for the Premium plan.
    </p>
  </div>
</div>

<div >
  <div >
    <h3>What is the maximum file upload size?</h3>
    <button ><img src="images/icon-arrow-down.svg" /></button>
  </div>
  <div >
    <p>
      No more than 2GB. All files in your account must fit your allotted storage space.
    </p>
  </div>
</div>

CodePudding user response:

The issue is because .accordionAnswers is not a child of .accordionQuestions, they're siblings. You need to use the operator in your CSS selector:

.accordionQuestions.active   .accordionAnswers {
  display: block;
}

Here's a full working example:

const btns = document.querySelectorAll('.btn')

btns.forEach(btn => {
  btn.addEventListener('click', () => {
    btn.parentNode.classList.toggle('active')
  })
});
.accordionAnswers {
  display: none;
}

.accordionQuestions.active   .accordionAnswers {
  display: block;
}
<div >
  <div >
    <h3>How many team members can I invite?</h3>
    <button ><img src="images/icon-arrow-down.svg"/></button>
  </div>
  <div >
    <p>
      You can invite up to 2 additional users on the Free plan. There is no limit on team members for the Premium plan.
    </p>
  </div>
</div>

<div >
  <div >
    <h3>What is the maximum file upload size?</h3>
    <button ><img src="images/icon-arrow-down.svg" /></button>
  </div>
  <div >
    <p>
      No more than 2GB. All files in your account must fit your allotted storage space.
    </p>
  </div>
</div>

  • Related