0

I have the following code that works as expected:

(async () => {
  const first = document.getElementById("first"), second = document.getElementById("second");
  try {
    first.innerHTML = await (await fetch('https://myAPI.com/1')).text();
    second.innerHTML = await (await fetch('https://myAPI.com/2')).text();
  } catch {
    first.innerHTML = 'Error';
    second.innerHTML = 'Error';
  }
})();

But I am curious whether there is a way to shorten the declaration of my variables, something like this (which doesn't work):

(async () => {
  const [first, second] = document.getElementById("[first, second]");
  try {
    first.innerHTML = await (await fetch('https://myAPI.com/1')).text();
    second.innerHTML = await (await fetch('https://myAPI.com/2')).text();
  } catch {
    first.innerHTML = 'Error';
    second.innerHTML = 'Error';
  }
})();

Just curious as to whether I can get rid of that second appearance of 'document.getElementById' to make the line more compact.

Ben
  • 1
  • Does this answer your question? [GetElementByID - Multiple IDs](https://stackoverflow.com/questions/14408891/getelementbyid-multiple-ids) – Giusè Reichardt Feb 08 '22 at 19:15
  • `const [first, second] = ["first", "second"].map(id => document.getElementById(id));` or `const [first, second] = document.querySelectorAll("#first, #second");` –  Feb 08 '22 at 19:18
  • I'm thinking you may get more answers if you remove the try/catch block and anonymous wrapper function from your examples. If I'm understanding the question correctly, they aren't really pertinent. – Andy Corman Feb 08 '22 at 19:19
  • Here's a way without duplicate code: https://jsfiddle.net/u3rqn78L/ –  Feb 08 '22 at 19:27
  • Are you sure it's working as expected? There's a) no http error handling b) no handling of the elements not being found c) waiting for the first request before doing the second, while it could do them concurrently d) resetting the first html to display `Error` even if only the second one failed – Bergi Feb 08 '22 at 19:33

1 Answers1

0

The most concise way to do it is by using the following:

const [first, second] = document.querySelectorAll("#first, #second");
EJZ
  • 1,142
  • 1
  • 7
  • 26
  • …except this doesn't work when the elements are in a different order in the dom, or if there's only one of them – Bergi Feb 08 '22 at 19:33