Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript how to for loop different elements as a variable to apply in same functions

I’m new to JavaScript,this question may looks very silly.

I have function like this:

  document.addEventListener('mouseup', function(e) {
        var container = document.getElementById('mySelectOptions');
        if (!container.contains(e.target)) {
            container.style.display = 'none';
        }
    });

And another almost same function like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  document.addEventListener('mouseup', function(e) {
        var container = document.getElementById('newSelectOptions');
        if (!container.contains(e.target)) {
            container.style.display = 'none';
        }
    });

The only difference is the id ,my question is how to add the 2 ids into this same function ?

maybe something like this:

for id in ['mySelectOptions','newSelectOptions']:
      document.addEventListener('mouseup', function(e) {
    var container = document.getElementById(id);
    if (!container.contains(e.target)) {
        container.style.display = 'none';
    }
});

>Solution :

You can do that with .querySelectorAll to select all match elements with different id. These id can be write with , splitter (#newSelectOptions,#mySelectOptions).

document.addEventListener('mouseup', function(e) {
    var containers = document.querySelectorAll('#newSelectOptions,#mySelectOptions');
    [...containers].forEach(function(container) {
        if (!container.contains(e.target)) {
            container.style.display = 'none';
        }
    });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading