Multiple Accordion Nesting Using Vanilla JavaScript

Viewed 132

I am trying to achieve multiple accordion lists with dynamic height concepts, I am debugging for hours and not able to understand where I went wrong. The code I have tried so far.

The scenario I was trying on is when the main categories are clicked with the dynamic height it will show off and that same scenario will happen for its sub-categories also. I am stuck on how to take the inner sibling method.

Note: I am trying to achieve this in vanilla javascript.

Any help will be appreciated !!

var headers = document.querySelectorAll('.first-ul-1 .ul, .sub-ul-1-a ul');
    window.addEventListener("DOMContentLoaded", () => {
        for (var i = 0; i < headers.length; i++) {
            headers[i].addEventListener('click', openAccordion);
        }

        function openAccordion(e) {
            var parent = this.parentElement;
            var article = this.nextElementSibling;

            if (!parent.classList.contains('open')) {
                parent.classList.add('open');
                article.style.maxHeight = article.scrollHeight + 'px';
            } else {
                parent.classList.remove('open');
                article.style.maxHeight = '0px';
            }
        }
.drop-down-menu,
.sub-ul-2-a{
            max-height: 0px;
            overflow: hidden;
            transition: max-height 350ms ease-in-out;
        }
<nav id="navigation" class="main-nav">
    <ul class="main-nav-list first-ul-1">
        <li>
            <p href="#">Types</p>
            <div class="drop-down-menu">
                <div class="menu-container">
                    <ul class="main-nav-list sub-ul-1-a">
                        <li>
                            <a href="#">Type
                                of season</a>
                            <ul class="main-nav-list sub-ul-2-a">
                                <li>
                                    <a href="#">Summer
                                        </a>
                                </li>
                            </ul>
                        </li>
              
                    </ul>
                </div>
            </div>
        </li>
    </ul>
</nav>

0 Answers
Related