I'm wondering if there's an easy way for a script to loop through all images (possibly of a certain class) on my web page and change the sources of all these images to the same image. This is for an easter egg, and I'd like to avoid AJAX and libraries like jQuery.
3 Answers
You can just use document.getElementsByTagName() to get all <img> elements, like this:
var imgs = document.getElementsByTagName("img");
for(var i=0, l=imgs.length; i<l; i++) {
imgs[i].src = "someImage.jpg";
}
5 Comments
thejh
Voted for you because of
var i=0, l=imgs.length, didn't know that that works.Nick Craver
@thejh - yup, declare as many as you want...
.length can be expensive to check...or at least adds up since it's checked every loop, so best to take that out off the equation :)Nicky McCurdy
Thanks! This works perfectly, and that's a pretty cool trick.
Free Consulting
hm?
collection.length is not expensive at allNick Craver
@user205376 - sure it is especially in IE, test it yourself, you'll see the method above (accessing
.length once) is consistently faster: jsperf.com/length-comparisonfor ( var i = 0; i < document.images.length; i++ )
if ( document.images[i].className == 'certain-class' ) // caution: can have multiple classes
document.images[i].src = '/hello.jpg';
document.images is DOM2 adoption from prehistoric DOM0