I need to target all the img
elements inside .lazy-load-wrapper
class and add multiple attribute
to it . And I need to use querySelectorAll
but I encountered an error Uncaught TypeError: elmnt.setAttribute is not a function
. I think I need to loop the element
inside querySelectorAll
because it is a static Nodelist
, but how can I do that?.
Here are the codes:
function theLazyLoader () {
const eleAttributes = {
loading: 'lazy',
class: 'lazy-load-spinner',
};
function setMultipleAttributes(elmnt, attributesToSet) {
Object.keys(eleAttributes).forEach(i => {
elmnt.setAttribute(i, eleAttributes[i]);
});
}
const img = document.querySelectorAll('.lazy-load-wrapper img');
setMultipleAttributes(img, eleAttributes);
}
theLazyLoader();
img {
width: 400px;
height: 300px;
display: block;
margin: 10px auto;
border: 0;
}
.lazy-load-spinner {
background: url("https://cdn.pixabay.com/animation/2023/10/10/13/27/13-27-45-28_512.gif") center center/100px 100px no-repeat #F1F1FA;
}
<div class="lazy-load-wrapper">
<img src="https://ik.imagekit.io/demo/img/image1.jpeg?tr=w-400,h-300" />
<img src="https://ik.imagekit.io/demo/img/image2.jpeg?tr=w-400,h-300" />
<img src="https://ik.imagekit.io/demo/img/image3.jpg?tr=w-400,h-300" />
<img src="https://ik.imagekit.io/demo/img/image4.jpeg?tr=w-400,h-300" />
<img src="https://ik.imagekit.io/demo/img/image5.jpeg?tr=w-400,h-300" />
<img src="https://ik.imagekit.io/demo/img/image6.jpeg?tr=w-400,h-300" />
<img src="https://ik.imagekit.io/demo/img/image7.jpeg?tr=w-400,h-300" />
<img src="https://ik.imagekit.io/demo/img/image8.jpeg?tr=w-400,h-300" />
<img src="https://ik.imagekit.io/demo/img/image9.jpeg?tr=w-400,h-300" />
<img src="https://ik.imagekit.io/demo/img/image10.jpeg?tr=w-400,h-300" />
</div>