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

177
Vistas
How to select the first number of elements with querySelectorAll

For example, let's say I have 25 images in a webpage

My question is: how do I select the first 6 images so that I can change the setAttribute to something else.

But I don't want to do this

document.queryselectorAll('img')[0]
document.queryselectorAll('img')[1]
document.queryselectorAll('img')[2]
document.queryselectorAll('img')[3]
document.queryselectorAll('img')[4]
document.queryselectorAll('img')[5]

I need a much easier way to write all that Help🙏

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Why not do a loop?

Logic

First we use querySelectorAll() to query the DOM and store the NodeList in a variable images. Then we loop to change the elements attributes.

const btn = document.getElementById('doIt'),
      images = document.querySelectorAll('img');

function addImages(){
  for(let i = 0; i < 6; i++){
     images[i].setAttribute('src', `https://picsum.photos/id/${i}/100/100`);
  }
}

btn.addEventListener('click', addImages);
<img src=""></img>
<img src=""></img>
<img src=""></img>
<img src=""></img>
<img src=""></img>
<img src=""></img>
<img src=""></img>
<p>
<input type="button" id="doIt" value="add images"/>

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