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🙏
Why not do a loop?
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"/>