1

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...

2
  • i think document.getElementsByClassName returns an array Commented Feb 14, 2014 at 15:47
  • If you have jQuery which $(document).ready() looks like, then this is easier with jQuery. Commented Feb 14, 2014 at 15:49

5 Answers 5

3

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

Comments

3

If you want to use jQuery

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

Comments

1

Since you're already using jQuery, instead of:

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

You can use:

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

Comments

0

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()

Comments

0

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

});  

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.