I have the following code:
var images = document.getElementsByTagName('img');
if (screen.width > 640) {
for (var image in images) {
image = images[image];
console.log(image['src']);
}
}
There is only one image on the page, but for some reason the for ... in statement is looping through images three times. Why is this?
Example: http://jsfiddle.net/OliverJAsh/C8egs/
You're not just looping through the list of elements, but also the named methods:
lengthitemnamedItemThe correct approach is:
for (var i=0; i<images.length; i++) {
var image = images[i];
console.log(image['src']);
}
Instead of using document.getElementsByTagName('img'), you can also use document.images.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With