1

It is possible to combine getElementById with different id name? How to achieve it?

function onOpen(){
    var x1 = document.getElementById("header");
    var x2 = document.getElementById("menu");
    var x3 = document.getElementById("program");
    x1.style.filter = "blur(5px)"
    x2.style.filter = "blur(5px)"
    x3.style.filter = "blur(5px)"
}
  • 1
    What do you mean ? Give an example. The question is too broad to awnser for now. – Ionut Eugen May 31 '19 at 01:10
  • https://stackoverflow.com/questions/5338716/get-multiple-elements-by-id – juanvan May 31 '19 at 01:11
  • @IonutEugen he wants to not have to set each elements blur line by line, he wants to be able to do it all at once, or in a smaller code base. instead of Line by Line like shown. That's my take. – juanvan May 31 '19 at 01:12

2 Answers2

3

You could use querySelectorAll and than iterate using NodeList.forEach()

function onOpen(){
  const els = document.querySelectorAll("#header, #menu, #program");
  els.forEach(el => el.style.filter = "blur(5px)");
}

onOpen();
<div id="header">TEST</div>
<div id="menu">TEST</div>
<div id="program">TEST</div>

Or if you want to pollute HTML with an extra class, you could use

function onOpen(){
  const els = document.querySelectorAll(".onOpenBlur");
  els.forEach(el => el.style.filter = "blur(5px)");
}

onOpen();
<div class="onOpenBlur" id="header">TEST</div>
<div class="onOpenBlur" id="menu">TEST</div>
<div class="onOpenBlur" id="program">TEST</div>

that way, in the future, all you have to do is add the same class to any number of elements, instead of nesting a new ID into JS...
Pick the one that best fits. Or you can even use both: '#header, #menu, .onOpenBlur'

https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

A slightly different approach

Another idea would be to just add a class to body and let CSS do the magic:

function toggleOpen(){
  document.documentElement.classList.toggle('is-open')
}

toggleOpen();
.is-open .on-open-blur {
  filter: blur(5px);
}
<div class="on-open-blur" id="header">TEST</div>
<div class="on-open-blur" id="menu">TEST</div>
<div class="on-open-blur" id="program">TEST</div>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

Id's are unique so as far as I know you can't select more than one at a time. You can however select multiple classes with document.getElementsByClass and have one class specified for all of them.

Ionut Eugen
  • 481
  • 2
  • 6
  • 27