开发者

JavaScript image replace

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.


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";
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜