Reputation: 19
I'm trying to get the ID of each image when clicked on but I can't seem to find a method of doing so, I've managed to do so with the first image but am struggling with all of them. If someone could help me here that would be fantastic.
Thanks in advance.
function myFunction() {
var tagID = document.getElementsByTagName('img')[0].id;
document.getElementById("results").innerHTML = tagID;
}
<img src="http://server2.sulmaxcp.com/Images/gridDefault.png" draggable="false" id="A1" onclick="myFunction()">
<img src="http://server2.sulmaxcp.com/Images/gridDefault.png" draggable="false" id="A2" onclick="myFunction()">
<img src="http://server2.sulmaxcp.com/Images/gridDefault.png" draggable="false" id="A3" onclick="myFunction()">
<p id="results"></p>
Upvotes: 0
Views: 35
Reputation: 22524
You can pass event
to your function and access id from the images. Using event.target
, you can reference the object that dispatched the event.
function myFunction(e){
var imageId = e.target.id;
document.getElementById("results").innerHTML = imageId;
}
<img src="http://server2.sulmaxcp.com/Images/gridDefault.png" draggable="false" id="A1" onclick="myFunction(event)">
<img src="http://server2.sulmaxcp.com/Images/gridDefault.png" draggable="false" id="A2" onclick="myFunction(event)">
<img src="http://server2.sulmaxcp.com/Images/gridDefault.png" draggable="false" id="A3" onclick="myFunction(event)">
<p id="results"></p>
Upvotes: 2
Reputation: 117
You have hardcoded the image to use. [0] This ALWAYS uses the same image id to use.
You need to pass in the image you want to use and then get its id.
function myFunction(img) {
var tagID = img.id;
document.getElementById("results").innerHTML = tagID;
}
<img src="http://server2.sulmaxcp.com/Images/gridDefault.png" draggable="false" id="A1" onclick="myFunction(this)">
<img src="http://server2.sulmaxcp.com/Images/gridDefault.png" draggable="false" id="A2" onclick="myFunction(this)">
<img src="http://server2.sulmaxcp.com/Images/gridDefault.png" draggable="false" id="A3" onclick="myFunction(this)">
<p id="results"></p>
Upvotes: 2