0

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.

2

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.