Running a JavaScript loop that runs only a single time

When I click outside, I want all divs 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.

Answer №1

It's an interesting solution to a problem that was causing confusion. By reversing the loop, it became apparent that the dropdowns array was being affected by changes in the DOM. This resulted in only half of the divs being displayed due to the array getting shorter each time. The issue becomes more evident when there are more than 2 divs involved, as it only showed specific ones based on the changes made.

In the absence of class information, some placeholders were used for demonstration purposes which effectively hid the divs with the provided code.

The link below explains how modifying the DOM triggers re-evaluation of the array, making this behavior expected but not initially anticipated.

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>

Answer №2

Your code snippet is:

 var dropdowns = document.getElementsByClassName("my-select-dropdown block");
The method of selecting elements is similar to CSS. The goal is to select all elements with the block classes at any level within the parent my-select-dropdown, which is why you have included the space.

If you want to achieve this, consider using

document.querySelectorAll('.my-select-dropdown .block')
instead, as it will provide a collection of elements that match the query. I have used dots before your classes to signify them as in CSS.

You may find these resources helpful:

Document.querySelectorAll()

Element.querySelector()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the quickest method to forward a page to a different web address?

I am looking to direct traffic from my Blogger website to an external URL and have found two possible methods to do so: One option is to use a meta tag: <meta http-equiv="Refresh" content="0; url='https://google.com' Alternativ ...

When configuring three.js and node.js on a live server, encountered a SyntaxError due to an unexpected string while importing './style.css'

Having trouble getting a simple three.js website up and running on a live server (a2 shared hosting). Node.js is installed, but the start up file main.js doesn't seem to be reading properly. Completely new to Node. Starting the server results in an er ...

Extract precise information from a database using node.js

Hey there, I have set up routes for fetching data from my database. Here's what I have so far: router.get('/', expressAsyncHandler(async (req,res) => { const products = await Product.find({}) res.json(products) ...

Understanding the application of JSON data can be simplified by following these

I am looking to manipulate dates by either adding or subtracting them, but I am unsure of how to extract the dates from the other data present. var fetch = require('node-fetch'); fetch('https://api.nasa.gov/planetary/earth/assets?lon=100.7 ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...

Tips for populating selectsize JS automatically while editing the HTML form

I am currently working on a form that consists of 3 fields: 2 input text fields and 1 select dropdown menu. After adding data to the form, I encountered an issue when trying to edit the information. While the input text fields retain the old data as expe ...

Having trouble with a jquery link not working even after removing the 'disabled' class

I am currently using a script that disables links with the class "disabled" //disable links $(document).ready(function() { $(".disabled a").click(function() { return false; }); }); In addition, I have another script that toggles the disabled s ...

The $route.reload() function seems to be ineffective in Internet Explorer

I'm currently using AngularJs to develop an application. The issue I am encountering is related to data not being refreshed in IE, even after executing the $route.reload() function. Strangely enough, this problem only occurs in Internet Explorer and w ...

Each JSON entry deserves its own dedicated page

Recently, I've started using Contentful and have already created a few entries. Now, my goal is to create a simple dynamic page with subpages - essentially like a portfolio. What I envision is an index page with links to inner portfolio pages, each co ...

Generate a new web component using JavaScript

My HTML table looks like this: <table id = "rpttable" name = "rpttable"> <thead> Column Headers here... </thead> <tbody id = "rptbody" name = "rptbody"> data here <3 .... </tbody> </table> And in my ...

What is the best way to implement CSS properties on Material UI components?

I've recently started exploring Material UI, but I'm having trouble understanding how the spacing properties function. I'm trying to utilize the "spacing" feature for various elements, but it appears that it only works for "Box" components a ...

When storing array values in objects, only the first value is saved and is repeatedly replaced with the same value

As a newcomer to JavaScript, my programming skills are not very strong at the moment. I have been working on a web scraper that returns an array of information including names, posts, bios, and more using the following code: let infoOfPost = await newTab(b ...

What could be causing my application to hang on my local server?

Recently, I developed a NodeJS and Express MVC (or perhaps more accurately VC) app. Initially, everything worked smoothly until I integrated express-validator and included the middleware in the app file. This caused my localhost to freeze, displaying a GET ...

Tips on keeping the width and height in proportion to a 16:9 aspect ratio across all screen sizes

I am trying to keep the height and width proportional to a 16:9 aspect ratio on any screen size. The problem I am encountering is: I have a video on my website that follows a 16:9 aspect ratio format, with a width of 1280 and a height of 720. I calculate ...

Guide to invoking a function stored as a variable in JavaScript

Here is the code snippet I am working on: function myFunction(){ var bob = function() { alert("works"); } }; //document.getElementById("btn").addEventListener('click', bob); //calls the function } I am wondering how to call the bob func ...

Troubleshooting Highcharts container selection problem on Nexus 7 running version 4.2.1

Having a problem with Highcharts on my Nexus 7. When I touch the chart, the entire thing gets selected with a blue overlay, but this doesn't happen on other devices like the Nexus 4. Even when I try accessing demos from Highcharts website, the issue ...

What can possibly be the reason why the HttpClient in Angular 5 is not functioning properly

I am attempting to retrieve data from the server and display it in a dropdown menu, but I am encountering an error while fetching the data. Here is my code: https://stackblitz.com/edit/angular-xsydti ngOnInit(){ console.log('init') this ...

Having trouble parsing data in a jQuery REST call

After creating a web service using Slim Framework 3 in PHP, all data is returned using the following instruction: return $response->withJson($liste); I then created an HTML client using the "jquery.rest" plugin to view the JSON results. However, I am ...

Try utilizing a dynamically created JSON object in place of using d3.json

I spent a considerable amount of time trying to solve this issue, but unfortunately I was unsuccessful. I know how to render a d3 tree with an external file, but I'm struggling with how to do it with a generated object. I am retrieving a JSON object t ...

Tips on increasing the height of an element that is overflowing

When populating my timeline component with dynamically mapped data from an array, I encountered an issue where if I added more data causing the maximum height to be reached, the overflow-y element didn't display all content. Despite trying various sol ...