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.