How to select all existing images and add an attribute to them

Asked

Viewed 29 times

1

So I’m trying to select all the existing images and I came to develop this code

(function ($) {

    var elementsImg = document.getElementsByTagName('img'), len, i;

    for (i=0, len=elementsImg.length; i<len; i++) {  
       elementsImg[i].setAttribute('loading','lazy');     
    }  

})(jQuery);

However, in the devtools console it appears as inserir a descrição da imagem aqui

I would like to know a possible solution and what I am doing wrong.

  • You’re not doing anything wrong. The method setAttribute there is no return, so it appears undefined.

  • inspecting the images, they have the modified attributes?

  • @Andréwalker Yes, the attributes were modified but I thought that using the console.log the way I did above it would return the img elements that were added the attribute "loading". However now I understood by the explanation above and below why it is returning "Undefined".

1 answer

1


The code is apparently correct. You do not receive a return value in your browser console because of the behavior of the method setAttribute, that does not return any value. When no value is returned from an expression, it will display undefined console; including function call itself console.log will display the value that was passed as argument and undefined immediately thereafter, given that console.log does not return any value:

console.log(1)

1
undefined

To check if the attributes were inserted in the images you can use the method getattribute as in the example:

elementsImg[i].getAttribute('loading');

Returning the attribute value. If the method does not find the attribute it will return null.

  • Thank you very much! now I understand the reason for the return "Undefined".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.