I have multiple links on my page and I want to create the same event handler for all of them.
In the first example I am just using a selector and it creates the event handler correctly for both of the links:
$(document).ready(function () {
$('.link').on('click', function () {
alert($(this).text() + ' was clicked');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href='#' class='link'>Link1</a>
<a href='#' class='link'>Link2</a>
In the second example, I iterate through each element and create the event handler for every single one of them:
$(document).ready(function () {
$('.link').each(function(){
$(this).on('click', function(){
alert($(this).text() + ' was clicked');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href='#' class='link'>Link1</a>
<a href='#' class='link'>Link2</a>
Both are producing the same result, but why? Does jQuery selector already iterates through all the elements? Does jQuery selector always iterates all elements or only in certain scenarios?