Federico
Federico

Reputation: 1422

querySelectorAll is not working with data-srcset

I want to apply a class to all the horizontal imgs on the website.

I'm trying to use this function below but it doesn't work.
Any help would be greatly appreciated.

$(function() {
  var images = document.querySelectorAll('[data-srcset]');

  for (var i = 0; i < images.length; i++) {
    if (images[i].naturalWidth > images[i].naturalHeight) {
      $(images[i]).addClass('horizontal');
    }
  }
}) 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" data-srcset="https://cdn.pixabay.com/photo/2015/02/18/11/50/mountain-landscape-640617_960_720.jpg" alt=landscape>

Upvotes: 1

Views: 670

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

That is because the data:... image you provide is 1x1 and so the check for images[i].naturalWidth > images[i].naturalHeight fails.

Keep in mind that if you use the srcset attribute (instead of data-srcset) which is the default it will work as expected (but you need to use the load event of the page).


$(window).load(function() {
  var images = document.querySelectorAll('[srcset]');

  for (var i = 0; i < images.length; i++) {
    if (images[i].naturalWidth > images[i].naturalHeight) {
      $(images[i]).addClass('horizontal');
    }
  }
})
.horizontal{border:10px solid OliveDrab;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" srcset="http://www.dummyimage.com/400x200" alt=landscape>

<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" srcset="http://www.dummyimage.com/200x210" alt=landscape>

Upvotes: 2

Natsathorn
Natsathorn

Reputation: 1528

It's better to replace alt=landscape with alt="landscape".

both

var images = document.querySelectorAll('[data-srcset]');

and

var images = $('[data-srcset]');

works for me.

Your problem is if statement is not true. it's always go to else.

Try update your if statement by the following code.

if (images[i].naturalWidth > images[i].naturalHeight) {
    $(images[i]).addClass('horizontal');
    console.log(images[i]);
} else {
    console.log('else');
}

You'll see that it's always go to else.

Upvotes: 0

Related Questions