Sometimes, we want to get the ID of element that called a function with JavaScript.
In this article, we’ll look at how to get the ID of element that called a function with JavaScript.
How to get the ID of element that called a function with JavaScript?
To get the ID of element that called a function with JavaScript, we can use the evt.target.id
property.
For instance, we write
document.getElementById("preview").onmouseover = (evt) => {
console.log(evt.target.id);
};
to get the element with getElementById
.
Then we set its onmouseover
property to a function that runs when we move our mouse over the element.
In it, we use evt.target.id
to get the ID of the element that we moved our mouse over.
Conclusion
To get the ID of element that called a function with JavaScript, we can use the evt.target.id
property.