Assume I need to set up 'click'
event listener on <div class="cool-div">
. And let's say it has an ancestor.
<div class="cool-ancestor">
...
<div class="cool-div">
...
</div>
Which of the following code I should use for better performance and why?
a) $(document).on('click', '.cool-div', function(){...})
b) $('.cool-ancestor').on('click', '.cool-div', function(){...})
c) $('.cool-div').on('click', function(){...})
Situation 1
- There is the only one
<div class="cool-div">
on the page.
Situation 2
- There are many
<div class="cool-div">
on the page.
b)
because I don't have to wait forDOMContentLoaded
for my scripts to work. So even if the page is not finished loading my buttons already work.