Sometimes, we want to get the ID of the clicked button on click with JavaScript.
In this article, we’ll look at how to get the ID of the clicked button on click with JavaScript.
How to get the ID of the clicked button on click with JavaScript?
To get the ID of the clicked button on click with JavaScript, we can get the id
property of the element clicked.
For instance, we write
<button id="1">B1</button>
<button id="2">B2</button>
<button id="3">B3</button>
to add 3 buttons.
Then we write
document.onclick = (e) => {
console.log(e.target.id);
};
to set document.onclick
to a function that’s called when we click on anything on the page.
And we can get ID of the element that’s clicked with e.target.id
.
Conclusion
To get the ID of the clicked button on click with JavaScript, we can get the id
property of the element clicked.