Reputation: 53
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
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