0

I might be confused but it seems like sometimes one of these two ways works when the other one fails.

Let's say the html is like this:

<div class="content">
    <div class="nestedDeep">
        <div class="clickMe">ClickMe</div>
    </div>
</div>

</br>

<div class="clickMe">ClickMe</div>

Am I imagining it or is there a clear difference between saying:

<script>


    $('.content .clickMe').click(function () {

        alert('you clicked');

    }); 


</script>

Or saying:

<script>


    $('.content').find('.clickMe').click(function () {

        alert('you clicked');

    })


</script>

Is one of those methods preferable over the other and if so, what's the main difference?

user44109
  • 121
  • 6
  • There's no difference in the results. The first may be slightly faster since you're only calling one function instead of two. – Barmar Jul 29 '20 at 18:40
  • In your code example the result would be equivalent and either is acceptable. jQuery gives you many ways to skin the same cat – j08691 Jul 29 '20 at 18:40
  • @j08691 Is there a situation in which one method would not work over the other? I could svear that sometimes the $('.content .clickMe') way seems to have failed while .find() worked. But I'm not sure what could cause that. – user44109 Jul 29 '20 at 18:44
  • 1
    See https://stackoverflow.com/questions/16308405/css-selectors-vs-jquery-traversal and https://stackoverflow.com/questions/19282458/when-to-use-jquerys-find – j08691 Jul 29 '20 at 18:46

0 Answers0