Is there any way to select all images of a certain size in Javascript? [on hold]

86
August 12, 2019, at 1:40 PM

I want to select all the images on a webpage bigger than a certain size, say 200 x 200 pixels. Is there any way to do this in Javascript?

Answer 1

Try this.

let img = document.querySelectorAll('img'), 
  len = img.length, 
  counter = 0; 
 
[].forEach.call(img, function(img) { 
  img.addEventListener('load', () => { 
    counter++; 
    if (counter === len) { 
      console.log('all images loaded at ' + new Date().toLocaleTimeString()); 
      check(); // call automatically without user interaction 
    } 
  }, false); 
}); 
 
check(); // just to show it works only after all image loads 
 
function check(size) { 
  if (counter !== len) { 
    console.log('waiting for images to load at ' + new Date().toLocaleTimeString()); 
    return; 
  } 
  let result = {}; 
  img.forEach(e => { 
    if (!result[e.naturalHeight + 'x' + e.naturalWidth]) { 
      result[e.naturalHeight + 'x' + e.naturalWidth] = []; 
    } 
    if (size && e.naturalHeight >= size && e.naturalWidth >= size) { 
      result[e.naturalHeight + 'x' + e.naturalWidth].push(e.src); 
    } else if (typeof(size) == 'undefined') { 
      result[e.naturalHeight + 'x' + e.naturalWidth].push(e.src); 
    } 
  }); 
  console.log(result); 
}
.container { 
  display: grid; 
  grid-template-columns: 1fr 1fr; 
  grid-gap: 1em; 
} 
 
img { 
  max-width: 100%; 
}
<button onclick="check()">Check Size</button> 
<button onclick="check(600)">Check Size > 600</button> 
<div class="container"> 
  <img src="https://dummyimage.com/400x400/000/fff" /> 
  <img src="https://dummyimage.com/600x400/000/fff" /> 
  <img src="https://dummyimage.com/400x400/000/fff" /> 
  <img src="https://dummyimage.com/600x400/000/fff" /> 
  <img src="https://dummyimage.com/600x600/000/fff" /> 
</div>

READ ALSO
Can&#39;t convert URI to ImageData on iOS

Can't convert URI to ImageData on iOS

Using JavaScript, I am trying to take a file from an input and convert its data URI into an ImageData valueThis is properly working on desktop where a file from a location is loaded

55
Monte Carlo simulation for p value

Monte Carlo simulation for p value

I'm creating a back testing tool for trading, and after some reading determined that Monte Carlo Simulations can be a very good tool to establish the statistical significance of the initial results

94
Export contents with image from web page to Microsoft Word - javaScript [on hold]

Export contents with image from web page to Microsoft Word - javaScript [on hold]

I am trying to export a web page with images to a Microsoft Word document or rtf

54
React - render CSS animation onClick

React - render CSS animation onClick

I'm new to React, sorry if this is too basic

114