Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

321
Views
javascript: Create variables/const for all elements in qureySelectorAll

I have multiple in my code, each with class="output" and unique IDs.

<p>Workers: <span class="output" id="workersOutput">0</span><span class="output" id="workersProdOutput"></span></p>

I want to use querySelectorAll to get them addressable in js via variables/const so that I can change their values with textContent.

Individually, I would do the following to find each div, and then the second line to update it on screen.

const workersOutput = document.getElementById('workersOutput');
workersOutput.textContent = `${workers}`;

This is really messy though when I'll have many of these to do (12 at the moment, more to come).

Using querySelectorAll, I can make some hybrid version, using their individual index numbers from the node list. It's not exactly readable or easy to use, as the data attached to each is only visible if I output it somewhere. Not to mentioned if I add more divs, those numbers will change and not be assigned to the same IDs anymore.

const outputs = document.querySelectorAll('.output');
outputs[2].textContent = `${workers}`;

Couldn't I use maybe forEach to create a variable for each using the ID attached to that index number? Or something along the lines of the below example (I know that's not how that works, but I want to get the idea across):

const outputs = document.querySelectorAll('.output');

outputs.forEach((output) => {
    const outputs[2] = document.getElementById(output.id);
});

I could also be way off on how to accomplish this the "right way", I'm newish to coding.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Use an object whose property names are the IDs.

const outputs = {};
document.querySelectorAll(".output").forEach(el => outputs[el.id] = el);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!