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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With