Event Listener On List Of Html Elements
I have multiple elements in DOM with the same class name - 'ps__rail-y'. I want to iterateover those elements and listen to click event on individual element with the class and sto
Solution 1:
First document.getElementsByClassName('ps__rail-y')\[index\]
is really bad code.
Really, the best thing to do is to utilize "event delegation", where you only set up one event handler at an ancestor of all the elements that "might" trigger the event and let the event bubble up to that ancestor. Then, when it is handled at the ancestor, you can reference the event.target
, which will reference the actual element that initiated the event. This way, you only set up one handler instead of many and you do it without any looping.
Here's an example:
// Set up the handler at an ancestordocument.querySelector("section").addEventListener("click", function(event){
// Only act if the actual element that triggered the event// has a certain classif(event.target.classList.contains("foo")){
console.log("You clicked the " + event.target.nodeName + " element.");
}
});
<section><divclass="foo">Click me</div><h1class="foo">Click me</h1><div>Click me <span>Click me</span></div><p>Click me</p><ahref="#"class="foo">Click me</a></section>
Post a Comment for "Event Listener On List Of Html Elements"