I recently had a question. In javascript using onclick() and getElementsByClassName requires looping through all the elements. My question is if this is done enough times, can it affect performance? Is there another alternative? Thank you
ahref=document.getElementsByClassName('btnClick');
for (var i=0; i < ahref.length; i++) {
ahref[i].onclick = function(){
alert('hola');
}
};
<a href="javascript:void(0)" class="btnClick">Click1</a>
<a href="javascript:void(0)" class="btnClick">Click2</a>
<a href="javascript:void(0)" class="btnClick">Click3</a>
For cases like the one you raise, where you want to establish the same event handler for multiple DOM elements, a technique called event delegation is usually used .
It has less of a performance hit, plus a much simpler syntax.
You can read more about it here https://javascript.info/event-delegation
In a nutshell, it consists of binding the event listener to the parent element that contains all the elements you want to track, instead of binding it to the elements themselves. As a wildcard parent element you can also use document , since it is the element that everything descends from.
Then, conditionals are used to apply the event handlers only to the elements that interest you, filtering by any condition: class, id, tag...
You can use as many conditionals as you like within each event listener .
The attached example would look like this using event delegation:
EDIT : In response to the second comment.
If there were multiple .div_parent elements and you wanted to bind the event handler ONLY to the child .btnClick elements of any .div_parent:
As much
element.querySelector('selector-css')
aselement.matches('selector-css')
they accept any valid css selector, as complex as you like.Beyond the style that each one has to iterate:
Adding an eventListener (that's what you're doing behind the scenes) to a batch of elements will always have to be done by iterating over the collection of elements.
The other option you have is to add
a
the property to each elementonclick
instead of doing it programmatically.One option you have to avoid constantly declaring anonymous functions for each element is to always use the same named function outside the loop, for example:
and in your
onclick
instead of putting your anonymous function putsayHi()
or in the callback of your eventListener ofclick
.