So, here is what I am wondering about. I have a code snippet like the one I attached.
This code runs just fine, what I am doing here is getting all the html elements with a class selector, and binding a predefined function on those elements click event.
My question is, when I have a thousands of elements, or even more. should I just run a loop like this and assign the function or is there any better or more efficient way to do this with pure JavaScript ?
If this is the most efficient one, and there is none other, or there are other ways, some references or explanation would really helpful, I found no relevant information anywhere else.
var elements = document.getElementsByClassName('element');
var printNumbers = function() {
this.innerHTML = this.dataset.position;
}
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener("click", printNumbers);
}
.element {
height: 40px;
width: 40px;
display: block;
float: left;
background-color: #cecece;
margin: 5px 0 0 5px;
}
<div class="element" data-position="1"></div>
<div class="element" data-position="2"></div>
<div class="element" data-position="3"></div>
<div class="element" data-position="4"></div>
<!-- more elements here with continious data-position attribute -->
<div class="element" data-position="1000"></div>