0

I'm using vanilla JavaScript and I'm trying to change the attribute "aria-expanded" from "false" to "true" on my HTML on click to then make it expand with CSS style as an accordion like FAQ section. But when I check the HTML (on chrome's DevTools) it doesn't change the attribute when I click on the button. This is the HTML:

        <div class="faq-questions-container">
            <div class="accordion" aria-expanded="false" role="button">
                <h3 class="faq-question">
                    <i class="fas fa-info-circle"></i>
                    Lorem Ipsum is simply dummy text of the printing?
                </h3>
                <p class="faq-answer">Lorem Ipsum is simply dummy text of the printing and typesetting industry. 
                    Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
                    when an unknown printer took a galley of type and scrambled it to make a type specimen book.
                </p>
            </div>
            <div class="accordion" aria-expanded="false" role="button"></div>
            <div class="accordion" aria-expanded="false" role="button"></div>
            <div class="accordion" aria-expanded="false" role="button"></div>

        </div>
    </div>

And this is the JS code:

 let accordions = document.querySelectorAll('.accordion');

 let showAnswer = () => {

    let ariaAttribute = this.getAttribute('aria-expanded');

    for (let i = 0; i < accordions.length; i++) {
        accordions[i].setAttribute('aria-expanded', 'false');
    }

    if (ariaAttribute === 'false') {
        this.setAttribute('aria-expanded', 'true');
    }
}

accordions.forEach(accordion => accordion.addEventListener('click', showAnswer));

Thanks for the help.

Adrian
  • 1
  • 1
  • 2
    "But when I check the HTML" - how exactly are you doing this? – Joseph Jan 20 '21 at 21:47
  • If you are just viewing source, you won't see a change as that is the source of the page as it was when the page was loaded. You will need to right click and inspect the element (chrome) or inspect it however your browser does – imvain2 Jan 20 '21 at 21:48
  • 2
    Arrow function paired with event handler paired with `this` reference === problem – Taplar Jan 20 '21 at 21:48
  • @Taplar This could use a more detailed answer even if you are correct. – Deadron Jan 20 '21 at 21:51
  • @Deadron If that is not an appropriate duplicate, there are bound to be others that address this. Incorrectly using arrow functions with event bindings is not an uncommon problem. – Taplar Jan 20 '21 at 21:52

0 Answers0