Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda