Prabhakar rai Prabhakar rai - 7 months ago 15
HTML Question

Change only one character of all img src of a class using javascript

I want to change the src of all the images which are in the 'car-image' class.

But I do not have to change whole url. I just want to change one character.

I want edit this -

<div class="car-image">
<img src="/cars/3_large_1.png">
</div>


To this-

<div class="car-image">
<img src="/cars/3_large_2.png">
</div>


And this format is common in all the image in this class.
I tried something like this-

var allsrc = document.getElementsByClassName('car-image');
allsrc[0].src="/cars/3_large_2.png";


This is not working.
How can i do this in javascript?

Answer

you are setting src of wrong node allsrc returns your div not the image.

Try this

allsrc[0].childNodes[1].setAttribute("src","/cars/3_large_2.png")
Comments