'How to Pass Element As Argument In Event Listener
I have a program that has a large number of reusable elements that all need an event listener. Because of this, I need a way to get the element from the listener. Here is what I want to do in code:
document.querySelectorAll(".class").forEach(function(el) {
el.addEventListener("click", function(element/*The element that the event listener is assigned to, passed as an argument*/) {
console.log(element) //Print out the element that was clicked in the console
})
})
Is there any way to replicate this or something of the sort in JavaScript?
Solution 1:[1]
In Javascript, you can reference variables in outer blocks/functions without having to pass them into inner functions:
document.querySelectorAll(".class").forEach(function(el) {
el.addEventListener("click", function(element) {
console.log(el);
})
});
If the element that triggers the click is the .class itself (rather than one of .class's descendants), you can also use event.target to identify it:
document.querySelectorAll(".class").forEach(function(el) {
el.addEventListener("click", function(event) {
console.log(event.target);
})
});
If you have to pass the element as a parameter to a function for some reason rather than accessing the element in the outer scope, I suppose you could usebind:
document.querySelectorAll(".class").forEach(function(el) {
el.addEventListener("click", logElement.bind(null, el));
});
function logElement(element) {
console.log(element);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CertainPerformance |
