简体   繁体   中英

retrieve getAttribute of clicked element in 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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM