Yash Mittal
Yash Mittal

Reputation: 53

Assign src of image into 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

<img src="image.jpg" id="img">
<span id="source"/>

JS ???

I want to assign the image source "image.jpg" to a variable and then load it through id "source" when I click on the image in HTML. How can I do it?

Thanks in advance.

Upvotes: 0

Views: 3292

Answers (2)

Markus Mauksch
Markus Mauksch

Reputation: 397

Not really quite clear what you want to achieve. Getting the content of the src tag is pretty easy and i got that working so far. But i'm not really sure if you now want to replace the id attribute of the span tag or what.

What i've solved so far: get the src

html:

<img src="image.jpg" id="img">
<span id="source" />

js:

var src = document.getElementById("img").getAttribute("src");
document.getElementById("source").innerHTML = src;

Demo on: https://jsfiddle.net/6oprtnv6/

So please clarify your second part

Upvotes: 0

Alaeddine Khelifi
Alaeddine Khelifi

Reputation: 71

The answer to the first part of your question is this:

var src = document.getElementById("img").getAttribute("src");

the second part is unclear

.. and then load it through id "source" in HTML.

Upvotes: 1

Related Questions