1

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 3

3

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";
}
Sign up to request clarification or add additional context in comments.

5 Comments

Voted for you because of var i=0, l=imgs.length, didn't know that that works.
@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 :)
Thanks! This works perfectly, and that's a pretty cool trick.
hm? collection.length is not expensive at all
@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-comparison
1

document.querySelectorAll("img").forEach((img) => img.src = "someimage.png");
<img src="broken1">
<img src="broken2">
<img src="broken3">

Comments

1
for ( 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.