How can I get the img.src back by clicking on the image using javascript?

I am trying to create a function with javascript where the user, by clicking on the image, can get these src images as url. I am very new to javascript and my attempts so far to create a function activated by the "onclick" of an image is this:

var showsrc = function(imageurl)
var img = new Image();
img.src = imageurl
return img.src


to trigger the results I was trying to embed image.src in my html using



I have very little success. Any help would be greatly appreciated. Thank.


source to share

4 answers

I've tested this in IE9 and Chrome 17. Add an onclick handler to the body (or the closest container for all your images) and then check if the clicked element is an image. If so, please include the URL.

var body = document.getElementsByTagName('body')[0];
body.onclick = function(e) {
    if (e.srcElement.tagName == 'IMG')    alert(e.srcElement.src);  




I think you want something like this:

See the code here:


<div id="urldiv">KEINE URL</div>
    <img src="" onclick="picurl(this);">
    <img src="" onclick="picurl(this);">


picurl = function(imgtag) {
    document.getElementById("urldiv").innerHTML = imgtag.getAttribute("src");




Image tags do not have "innerHTML" as they are single dot tags - they cannot have children. If your x

id is the image tag itself, then:



spits out src images.



Here's a naive solution with javascript only (possibly not cross-browser compatible):

<!doctype html>
      function init() {
        var images = document.getElementsByTagName('img');

        for(var i = 0, len = images.length; i < len; i++) {
          images[i].addEventListener('click', showImageSrc);

      function showImageSrc(e) {
  <body onload="init()">
    <img src="">




All Articles