Your code seems to be working for images of the correct dimensions. However, you can change your code a little. For the code that you've given you don't need to do:
img = document.getElementsByTagName("img")[i];
in your for loop at each iteration, as this is an expensive function to run. Instead, you already have the result of document.getElementsByTagName("img");
stored in imgs
, so you can use that instead:
img = imgs[i];
See working example below:
$(document).ready(function() {
var imgs = document.getElementsByTagName("img");
var imgSrcs = [];
for (var i = 0; i < imgs.length; i++) {
img = imgs[i];
var width = img.clientWidth;
var height = img.clientHeight;
if (width < height) {
img.setAttribute('style', 'transform:rotate(90deg)');
}
};
});
img {
height: 150px;
width: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Width > Height</p>
<img src="https://media.wired.com/photos/5926db217034dc5f91becd6b/master/w_1904,c_limit/so-logo-s.jpg" />
<p>Width < Height</p>
<img src="https://d1qb2nb5cznatu.cloudfront.net/startups/i/32728-274244db60c65e1cc32abb4c54a2c582-medium_jpg.jpg?buster=1442602512" />
<p>Width < Height</p>
<img src="https://images.unsplash.com/photo-1522092787785-60123fde65c4?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=94d6ebf03fdc6a3c8159ac9aeceb0483&w=1000&q=80" />
Also, since your using jQuery, this can be done even easier using jQuery methods:
$(document).ready(function() {
$('img').each((_, elem) => {
let width = $(elem).width();
let height = $(elem).height();
if(width < height) {
$(elem).css({'transform': 'rotate(90deg)'});
}
});
});
img {
height: 150px;
width: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Width > Height</p>
<img src="https://media.wired.com/photos/5926db217034dc5f91becd6b/master/w_1904,c_limit/so-logo-s.jpg" />
<p>Width < Height</p>
<img src="https://d1qb2nb5cznatu.cloudfront.net/startups/i/32728-274244db60c65e1cc32abb4c54a2c582-medium_jpg.jpg?buster=1442602512" />
<p>Width < Height</p>
<img src="https://images.unsplash.com/photo-1522092787785-60123fde65c4?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=94d6ebf03fdc6a3c8159ac9aeceb0483&w=1000&q=80" />