Denoteone Denoteone - 1 year ago 85
CSS Question

Get Image info and show in console on page resize

Question: How would I collect the src, width and height of all the images on a page and then each time that current page changes size show the image info in the console.

Example Code:

var images = document.getElementsByTagName('img');
var srcList = [];
for(var i = 0; i < images.length; i++) {

for(var i = 0; i < images.length; i++) {
//I am pretty sure I would have to go get the new width and height of the images on the page. Should I just loop through and populate the array like above? The source would stay the same.

I am not sure how to update the array correctly with the image info and once I have it all access it to show it in the console log.

Answer Source

document.getElementsByTagName returns a live HTMLCollection of elements that match the tagname. Live means that any modification in the document will be reflected in the collection. As such, you only need to create the collection once, and it will have live data every time you query it.

So you can do something like this:

var images = document.getElementsByTagName('img');
window.addEventListener('resize', function() {
  for(i=0; i<images.length; i++) {
    console.log(images[i].src, images[i].width, images[i].height);

And it will always show the actual data of the images.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download