Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve getAttribute of clicked element in javascript

Tags:

javascript

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

like image 996
Nomad Avatar asked Jul 16 '26 07:07

Nomad


1 Answers

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>
like image 189
Arun P Johny Avatar answered Jul 18 '26 20:07

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!