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

165
Views
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 answers
Answer question

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 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!