When I click outside, I want all div
s with my-select-dropdown
and block
classes to disappear simultaneously instead of one by one. The current code doesn't produce any errors but hides the divs individually on each click. How can I make them all disappear at once?
This is my existing code:
window.addEventListener("click", function (e) {
var dropdowns = document.getElementsByClassName("my-select-dropdown block");
console.log(dropdowns.length)
for (var i = 0; i < dropdowns.length; i++) {
console.log(dropdowns[i])
if (e.target.closest('.my-select > button')){
// continue
}
else if (e.target !== dropdowns[i] && !e.target.closest(dropdowns[i].classList)){
dropdowns[i].classList.replace("block", "hidden");
}
}
});
The console log
shows 2 with only one HTML element
, indicating that only the first loop is being executed.