'Dropdown menu - always showing the last div

there!

I would like to ask you how can I open the correct dropdown with JS. It is working, but no matter which I am clicking it is always showing me the last dropdown div. The piece of code that I have marked should help with this problem, but it doesn't work.

<div class="dropdown-wrapper" data-dropdown>
<a class="dropdown-link" href="#" data-dropdown-button>Makeup</a>
<div class="dropdown-menu"></div>
document.addEventListener("click", e => {
    const isDropDownButton = e.target.matches("[data-dropdown-button]");
    if (!isDropDownButton && e.target.closest("[data-dropdown]") != null) return;
    let currentDropDown;
    if (isDropDownButton) {
        currentDropDown = e.target.closest("[data-dropdown]");
        currentDropDown.classList.toggle("active");
    }

//THIS CODE//

    document.querySelectorAll("[data-dropdown].active").forEach(dropdown => {
        if (dropdown === currentDropDown) return;
        dropdown.classList.remove("active");
    })
})

Thank you!



Solution 1:[1]

In JavaScript you are selecting the element by closest [data-dropdown], therefor add this on the DIV tags.

<div class="dropdown-wrapper" data-dropdown>
    <a class="dropdown-link" href="#" data-dropdown-button>Makeup</a>
    <div class="dropdown-menu" data-dropdown>
        <a class="dropdown-link" href="#" data-dropdown-button>1</a>
        <a class="dropdown-link" href="#" data-dropdown-button>2</a>
        <a class="dropdown-link" href="#" data-dropdown-button>3</a>
    </div>
</div>

your JavaScript works and no need to change it. by clicking the links 1,2,3 it will add a class="active" in the second div.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mehrwarz