3

i have number of images on my webpage.

<img id="a" src="1.jpg">
<br>
<img  id="b" src="2.jpg">

I am trying to get "src" of clicked images by using below javascript.

var getImageName = function(){
     document.onclick = function(){
        var image = this.getAttribute("src");
        alert(image);
        }}

getImageName();

But its giving an error this.getAttribute is not function.

Any idea? Thanks in advance

1 Answer 1

11

Because this is the document object in your click handler, so you may want to check whether the click has happened in an image element

var getImageName = function() {
  document.onclick = function(e) {
    if (e.target.tagName == 'IMG') {
      var image = e.target.getAttribute("src");
      alert(image);
    }
  }
}

getImageName()
<img id="a" src="//placehold.it/64X64&text=1" />
<br>
<img id="a" src="//placehold.it/64X64&text=2" />
<br>

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

4 Comments

can you please elaborate how this and target are different?
@Nomad since you have binded the handler to the document object, this inside the hadnler will refer to the document object
@Nomad Event.target will refer to the element which dispatched the event so it will be the image element
@Nomad see the Event object properties for details

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.