Yash Mittal
Yash Mittal

Reputation: 53

Assign src of image to a variable through JS in HTML

I want to assign content of the src tag of image to a variable on clicking on the image through JS: Eg-

HTML

<div id="img">
<img src="image1.jpg">
<img src="image2.jpg">
</div>
<span id="source"/>

JS ???

I want to assign the image source of the clicked image to a variable and then display the source on HTML through span. This all should happen when I click the image. And the source that is going to be assigned to variable should be of the clicked image.

How can I do it?

Thanks in advance.

Upvotes: 0

Views: 2242

Answers (2)

Anwarul Islam
Anwarul Islam

Reputation: 141

try the following:

<html>
  <head>

  <script>
      function setImage(id){
         var element = document.getElementById(id).src;
         document.getElementById("source").innerHTML = "<img src='" +   element + "' />";
      }

  </script>

  </head>

  <body>
         <div id="img">
           <img id="img1" src="image1.jpg" onclick="setImage(this.id)" >
           <img id="img2" src="image2.jpg" onclick="setImage(this.id)" >
         </div>
        <span id="source"></span>
   </body>
  </html>

Upvotes: 1

prabhat
prabhat

Reputation: 106

you can try this,

<img ng-src="{{myVar}}">

Upvotes: 0

Related Questions