Consider the following markup:
<div class="parent">
<div class="child">
button
</div>
</div>
I need to run a function on a click
event on the child
class and I've got the following two options:
$(".parent").on("click", ".child", function(){....});
and
$(document).on("click", ".child", function(){....});
Is there a dramatic difference on performance between using a direct parent
as a target and the document
itself? To me using document
seems as a more robust option (if the parent class was changed for instance) - just need to make sure it won't cause problems if I start using this method everywhere.
P.S. The child
is added dynamically inside the parent
hence I'm using .on()
$(".parent").on("click", ".child", function(){....});
binds your click event to only those elements with class '.parent' that are present within the document and the event is bubbled from the target('.child') to the element where the handler is attached. This is much preferable than adding it to document as, adding it to document like
$(document).on("click", ".child", function(){....});
Bubbles the click event from the target in the document where they occur all the way up to the body and the document element.
As @Woff mentioned, bound handlers wont get removed on removal of .parent elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With