Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

328
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda