Get ID Of Clicked Element In JavaScript
Learn how to get a value of an ID attribute of a clicked HTML Element in JavaScript using event object.
Here is the wrapper div with an id button-group that has four buttons in it.
Each button has an ID attribute.
<div id="button-group">
<button id="button-1">Button 1</button>
<button id="button-2">Button 2</button>
<button id="button-3">Button 3</button>
<button id="button-4">Button 4</button>
<button id="button-5">Button 5</button>
</div>
Get ID of Clicked Element Using For Loop
One of the ways to get an ID attribute of a clicked element is that you actually attach click events to all the buttons inside For loop.
Get DOM references to all the buttons by invoking getElementsByTagName() on the document object with an argument button.
Assign it to the constants buttons which will be an HTML Collection Object.
Iterate through buttons using for of loop.
Attach a click event to each button inside the loop with the buttonPressed() callback function.
The buttonPressed() callback function will have a returned event object which has all the data about the HTML element that is clicked on.
To get the clicked element, use target property on the event object.
Use the id property on the event.target object to get an ID of the clicked element.
const buttons = document.getElementsByTagName("button");
const buttonPressed = e => {
console.log(e.target.id); // Get ID of Clicked Element
}
for (let button of buttons) {
button.addEventListener("click", buttonPressed);
}
Try it out
See the Pen Get ID of Clicked Element in JavaScript by Raja Tamil (@rajarajan) on CodePen.
Get ID Of Clicked Element Using Parent Element
Instead of attaching a click event to each button, just attach one click event to the parent element of the buttons which is button-group with a callback function buttonGroupPressed().
Then, capture the clicked element by using target property on the event object.
const buttonGroup = document.getElementById("button-group");
const result = document.getElementById("result");
const buttonGroupPressed = e => {
const isButton = e.target.nodeName === 'BUTTON';
if(!isButton) {
return
}
console.log(e.target.id);
}
buttonGroup.addEventListener("click", buttonGroupPressed);
The target property on the event object will return the currently clicked element regardless if its a parent element (button-group) or child elements (button elements).
Check to see if the clicked element is a button element or the button group element.
If it’s a button element, use id property on the e.target to get an actual ID of the clicked element.
Try it out
See the Pen Get ID of Clicked Element in JavaScript (Using Parent Element) by Raja Tamil (@rajarajan) on CodePen.