1

I want all divs with my-select-dropdown and block classes to get unvisible at once when I click outside. Below code doesn't give me errors but makes divs dissapear one by one in every click. But I want all disappear at once.

My 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')){
                // pass
            }
            else if (e.target !== dropdowns[i] && !e.target.closest(dropdowns[i].classList)){
                dropdowns[i].classList.replace("block", "hidden");
            }
        }
    });

Console log returns 2 with only one HTML element which means there's only first loop which is being executed.

1
  • This is the problem document.getElementsByClassName("my-select-dropdown block"). If you select an element like this, use querySelectorAll()
    – kmp
    Dec 6, 2020 at 0:02

2 Answers 2

1

So, this is a tricky one. It turns out that if you reverse your loop, it works. For whatever reason, the dropdowns array is getting re-evaluated when you change the DOM, so your array is getting shorter and you are essentially only doing half your divs. You aren't seeing this because you apparently only have 2 of them. When I put in 4, it was much clearer, since it showed me Test1 and Test3 for the ids I changed it to display, instead of the full div.

I made up some stuff for the classes, since you didn't include that, but it seems to work to hide the divs with your code.

The link below says that changing the DOM will cause the array to re-evaluate, so this is expected, just not by me or apparently by you. :-)

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

window.addEventListener("click", function (e) {
        var dropdowns = document.getElementsByClassName("my-select-dropdown block");        
        console.log(dropdowns.length)
        for (var i = dropdowns.length-1; i >= 0 ; i--) {
            console.log(dropdowns[i].id)
            if (e.target.closest('.my-select > button')){
                // pass
            }
            else if (e.target !== dropdowns[i] && !e.target.closest(dropdowns[i].classList)){
                dropdowns[i].classList.replace("block", "hidden");
            }
        }
    });
.my-select-dropdown
{
  font-family: "Ariel";
}

.block
{
  display: block;
}

.hidden
{
  display: none;
}
<div id='test1' class="my-select-dropdown block" type="button">Test 1</div>
<div id='test2' class="my-select-dropdown block" type="button">Test 2</div>
<div id='test3' class="my-select-dropdown block" type="button">Test 3</div>
<div id='test4' class="my-select-dropdown block" type="button">Test 4</div>

4
  • There is no need for reverse engineering. It worked by changing GetElementsByClassName to QuerySelectorAll. Because as you stated GetElementsById is a live HTMLCollection so it affects the iteration process. Hence, your answer is pointing the root of the problem I can mark it as answer if you edit your answer. I think the function should stay the same and only GetElementsByClassName have to be changed. That's what I did.
    – Ulvi
    Dec 6, 2020 at 7:48
  • @Ulvi, well, if I changed my Answer to be what you say, then that changes quite a bit of my Answer to no longer be mine. You can always self-answer and say what you did. Also, this is not "reverse engineering". This is simply reversing the direction of your loop. merriam-webster.com/dictionary/reverse%20engineer Also, knowing that reversing a loop to make things work can make your life easier. Not everything has a exact replacement method that can be used without weird side effects, like this one. Dec 7, 2020 at 16:52
  • 1
    I read "reverse your loop" as "reverse engineer" :D That was really funny/silly misreading. Question is marked as duplicate so doesn't allow new answers and that's why I did that suggestion. Please don't take my previous comment offensive if did. Thank you for your solution and taking your time.
    – Ulvi
    Dec 9, 2020 at 20:05
  • @Ulvi, ok, and no, I didn't think your comment was offensive, just confusing. I just didn't think it'd be right to give me credit for suggesting a different method, even though I did essentially figure out the root cause. Also, I've misread things far worse than that. Some were similarly amusing and some..... not so much. I don't understand how using jquery all of a sudden makes your Q a duplicate. I don't like pushing a library on a project to solve one single issue that can be solved without it. But if you're already using it, that disagreement goes away. I'm glad you got an answer, anyway. Dec 9, 2020 at 20:52
1

This is your code var dropdowns = document.getElementsByClassName("my-select-dropdown block"); The way that you select elements it's like css. The idea it to selection all block classes at any level of the parent my-select-dropdown that why, you've put the space.

So you wan't to do thing like that, use instead document.querySelectorAll('.my-select-dropdown .block') that will return a collecton of elements that matches the query.I've added the dots for your classes like css.

You can read this:

Document.querySelectorAll()

Element.querySelector()

1
  • It works, thanks! I made some changes to my code and that was preventing the result at first. But that's not because these aren't returning same elements. The reason is getElementsByClassName() is a live HTMLCollection which affects iteration process.
    – Ulvi
    Dec 6, 2020 at 7:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.