-1
<strong class="logo">
<a href="/">
<img width="254" height="236" src="/themes/musika/images/logo.png" alt="logo"></img>
<span>text</span>
</a>
</strong>

Need to change image url by javascript. The HTML code cannot be changed.

user2456908
  • 9
  • 1
  • 1

6 Answers6

1

The HTML code cannot be changed.

No need to assume this is "the first img in your page" or to "add the id tag". You could just iterate over all the img tags and search for the element to be modified.

var imgs = document.getElementsByTagName("img");
for(var x = 0; x<imgs.length; x++){

if (imgs[x].scr == "/themes/musika/images/logo.png")
imgs[x].scr = "YOUR NEW IMAGE HERE"

}
Saturnix
  • 10,130
  • 17
  • 64
  • 120
1

if u can't change the code ... so u can't add id then

like already suggested

if the image is the first one

document.getElementsByTagName("img")[0].src="anotherimage.jpg";

function way

function changeimage(newimage){
document.getElementsByTagName("img")[0].src=newimage;
}
changeimage("anotherimage.jpg");

if u don't know if it's the first image then but u know the name then search it

var
imgs=document.getELementsByTagName('img'),
l=imgs.length;
while(l--){
 if(imgs[l].src=='/themes/musika/images/logo.png'){
  imgs[l].src='anotherimage.jpg';
 }
}

function

function changeimage(newimage){
    var
    imgs=document.getELementsByTagName('img'),
    l=imgs.length;
    while(l--){
     if(imgs[l].src=='/themes/musika/images/logo.png'){
      imgs[l].src=newimage;
     }
    }
}

changeimage('newimage.jpg');

cocco
  • 16,442
  • 7
  • 62
  • 77
0

Assuming this is the FIRST image on the page:

document.getElementsByTagName("img")[0].src = "c:\temp\newimg.jpg";

Obviously, change c:\temp\newimg.jpg to what you need.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
0
<img width="254" height="236" id="imageid" src="/themes/musika/images/logo.png" alt="logo"></img>



document.getElementById("imageid").src="image name";
PSR
  • 39,804
  • 41
  • 111
  • 151
0

Add an id to the tag : <img id="image1" width="254" height="236" src="/themes/musika/images/logo.png" alt="logo"> Then in the javascript use the following to point the new src.

document.getElementById("image1").src="path/newImg.png";
happybuddha
  • 1,271
  • 2
  • 20
  • 40
0

add a ID in you image tag

<img width="254" height="236"id="cng_img" src="/themes/musika/images/logo.png" alt="logo"></img>

Now you can change the image like below

var cngid = document.getElementById("cng_img");

cngid.src = "path/to/image.png";
S. Rasel
  • 2,841
  • 1
  • 16
  • 12