replacing all images from a class with another image using Javascript

情到浓时终转凉″ 提交于 2021-01-28 22:01:52

问题


I'm using an external script on my website with a form. Some of the css is customizable, but I can't change images for example. I would like to replace the small image displayed when a field is not completed by an other one using Javascript.

This is the HTML code with the original image :

<img class="incorrect-img" count="1" src="http://www.detailsdetails.eu/images/newimg/incorrect.gif"></img>

I'm trying with this Js code but it's not working...

$(document).ready(function () {

document.getElementsByClassName("incorrect-img").src="MYIMAGE.gif";

});  

Does anyone know what I'm doing wrong? Maybe it's because I'm trying to change an image from a class, maybe it only works with ID ? I can't change the class by ID...


回答1:


document.getElementsByClassName("incorrect-img") returns an HTMLcollection which is like an array but not quite.

Luckily you can loop over it like you would with an array:

var elems = document.getElementsByClassName("incorrect-img");
for (var i = 0; i < elems.length; i+= 1) {
    elems[i].src = "MYIMAGE.gif";
}



回答2:


If you want to use jQuery

$(document).ready(function () {
    $( ".incorrect-img" ).each(function( index ) {
        $(this).attr('src', 'MYIMAGE.gif');
    });
});



回答3:


Since you're already using jQuery, instead of:

document.getElementsByClassName("incorrect-img").src="MYIMAGE.gif";

You can use:

$(".incorrect-img").attr("src", "MYIMAGE.gif");




回答4:


document.getElementsByClassName() returns the elements of array which are matched with class selector, In your case there is only one image so 0 index would be fine for access the first element. like this

document.getElementsByClassName("incorrect-img")[0].src="MYIMAGE.gif";

For inormationa about `getElementsByClassName()




回答5:


thanks a lot. I combined your answers. here is my final code :

$(window).load(function() {

var image = $(".incorrect-img");
for (var i = 0; i < image.length; i++) {
image[i].src="incorrect_2.gif";
}

});  


来源:https://stackoverflow.com/questions/21783594/replacing-all-images-from-a-class-with-another-image-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!