0

I tried two approaches that both worked fine. Is there a reason I should use one over the other?

First Approach:

$('div.parent').find('.cancel-btn').on('click', function(){
  alert('cancel clicked');
});


Second Approach:

$('div.parent').on('click', '.cancel-btn', function(){
  alert('cancel clicked');
});
zeckdude
  • 15,877
  • 43
  • 139
  • 187
  • 2
    I'd say the second approach. The first approach you wouldn't even need the `.find()` if you used the selector `$('div.parent .cancel-btn')`. However, if it is a dynamic button then i believe you need the second approach – Adjit Nov 10 '16 at 22:25
  • It's not the right place to ask such questions... post it in http://codereview.stackexchange.com/ – Zakaria Acharki Nov 10 '16 at 22:28
  • @Adjit I'm pretty sure that `$('div.parent).find('.cancel-btn')` is better for performance than `$('div.parent .cancel-btn')`. That's why I used that there. – zeckdude Nov 10 '16 at 22:37
  • Can you send me where you saw that? I am curious, because I have never heard that before / seen it done that way. – Adjit Nov 10 '16 at 22:50
  • 1
    Have a look here - http://stackoverflow.com/questions/6230266/jquery-single-selector-vs-find – Adjit Nov 10 '16 at 22:51
  • @Adjit, I guess I had it backwards. Thanks for letting me know. – zeckdude Nov 10 '16 at 23:28

1 Answers1

0

From my reading of the docs they seem very similar except that the second one will fire the event even if the child element does not exist. Which is interesting.

And from that we could deduce that the first version wires up the click event listener on the target (.cancel-btn) element. It spends time finding that element when the listener is created, and there is no DOM traversal requirement when the click event fires the listener.

Meanwhile the second option wires a listener for the click event to the parent then searches out the child when the event fires.

Therefore in theory there will be a finite performance difference from the user perspective of the second option. Though the impact of that would depend on the element density and tree makeup of the page.

I guess in most cases the time impact is so small as to be unimportant. In which case the only true difference is the point about the second option firing irrespective of the presence of the child element.

Vanquished Wombat
  • 9,075
  • 5
  • 28
  • 67