Search code examples
javascripthtmldomconstantsselectors-api

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.


Solution

  • Use an object whose property names are the IDs.

    const outputs = {};
    document.querySelectorAll(".output").forEach(el => outputs[el.id] = el);