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:
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';
}
});
3
Answers
You can do that with
.querySelectorAll
to select all match elements with different id. These id can be write with,
splitter (#newSelectOptions,#mySelectOptions
).You can create a function that wrap your DOM function code
You can create an
array
of the Ids in case you do not want to work withclasses
.Keep in mind that I used the
let
for defining the array outside thefunction handler
body since it isblock-scoped
, you will need to declare it as var inside the function handler body so it can behoisted
and to avoid a new instance from being created each time the event is triggered