-2
<div class="logodiv">
        <a href="/"><img src="images/logoweb.png" alt=""></a>
    </div>

Hello, I need to change the image source from images/logoweb.png into a different files like logowebnew.gif. I have no access to HTMl for an edit or make an id for the img, how do I change the source using javascript?

  • Familiarize yourself with the [DOM API](//developer.mozilla.org/en/docs/Web/API/Document_Object_Model), especially [`querySelector`](//developer.mozilla.org/en/docs/Web/API/Document/querySelector). – Sebastian Simon Oct 23 '22 at 11:53

2 Answers2

0
Hi @Hardi Basalim

In that type of problem you could use the prototype chaining property of JavaScript as in explain in down below code.

 const changeMaker = document.getElementsByClassName("logodiv");

    function edit()
    {   
        changeMaker[0].childNodes[1].childNodes[0].src = "https://lh3.googleusercontent.com/a/ALm5wu1JKEg8-XY-8l4ncsyDQjRiXTHPkiaRFw5DUqbXWw=k-s192";
    }
    edit();

Here is Demo:-

const changeMaker = document.getElementsByClassName("logodiv");

function edit()
{   
    changeMaker[0].childNodes[1].childNodes[0].src = "https://lh3.googleusercontent.com/a/ALm5wu1JKEg8-XY-8l4ncsyDQjRiXTHPkiaRFw5DUqbXWw=k-s192";
}
edit();
<html lang="en">
  <head>
  </head>
  <body>
   <div class="logodiv">
        <a href="/"><img src="images/logoweb.png" alt=""></a>
    </div>
  </body>
</html>
DSDmark
  • 1,045
  • 5
  • 11
  • 25
0

I think like this. Thank you.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="logodiv">
        <a href="/"><img src="images/logoweb.png" alt=""></a>
    </div>
    <script>
        var a = document.getElementByClassName("logodiv")[0];
        a.firstElementChild.firstElementChild.setAttribute("src", "https://lh3.googleusercontent.com/a/ALm5wu1JKEg8-XY-8l4ncsyDQjRiXTHPkiaRFw5DUqbXWw=k-s192");
    </script>
    
</body>
</html>

x