Skip to content
Advertisement

loop document.getElementsByClassName

I should loop document.getElementsByClassName but first doing a check.

For just one element I would do this:

if (document.getElementsByClassName('lazyload img-responsive wp-post-image')[0].getAttribute('width') < 500){
document.getElementsByClassName('lazyload img-responsive wp-post-image')[0].setAttribute("srcset", " https://www......jpg ");}

But I have to repeat it for more elements and I never know how many there are. I would need such a loop but with the verification document.getElementsByClassName (‘lazyload img-responsive wp-post-image’) [0] .getAttribute (‘width’) <500 first.

var elements = document.getElementsByClassName('lazyload img-responsive wp-post-image');
for (var i = 0, l = elements.length; i < l; i++) {
    elements[i].setAttribute("srcset", " https://www......jpg  ");
}

How could I solve? Thanks

Advertisement

Answer

Not sure if your requirement is clear. Is it that, you need to check only element[0] for its width and then set srcset for all remaining elements? Or you need to test respective element[i] and the elements[i].setAttribute("srcset", " https://www......jpg ");

If 1st one is true then you can try:

var elements = document.getElementsByClassName('lazyload img-responsive wp-post-image');
if(elements[0].getAttribute('width') < 500){
    for (var i = 0, l = elements.length; i < l; i++) {
        elements[i].setAttribute("srcset", " https://www......jpg  ");
    }
}

If 2nd is true, then try:

var elements = document.getElementsByClassName('lazyload img-responsive wp-post-image');
for (var i = 0, l = elements.length; i < l; i++) {
    if(elements[0].getAttribute('width') < 500){
        elements[i].setAttribute("srcset", " https://www......jpg  ");
    }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement