user3007294
user3007294

Reputation: 951

different types of jQuery selectors

What’s the difference between $(“#foo .bar”) and $(“#foo”).find(“.bar”)?

$('#foo').on('click', function(){
  $(this).find('.bar').css('background-color', 'yellow');
})

$('#foo_two .bar_two').on('click', function(){
  $(this).css('background-color', 'red');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "foo">
    <p class= 'bar' style='background: green'> Hello there</p>
</div>

<div id = 'foo_two'>
    <p class = 'bar_two' style='background: orange'> Hello there</p>
</div>

In the snippet, I tried to outline what I thought was the difference but seem to now not know what's going on...

Upvotes: 0

Views: 67

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

$('#foo').on('click', function(){

means that the parent #foo is the click target Element

$('#foo_two .bar_two').on('click', function(){

... click on the parent #foo_two if you dare! http://jsfiddle.net/0qcssuue/2/

(.bar_two has now the click event bound to it. #foo_two just helped jQuery and the JS parser to find it's child .bar_two Element)

To conclude, the $(this) inside the function refers to the targeted Selector.
In the first case it's #foo,
in the second it's #foo_two .bar_two (the #foo_two's children .bar_two)

In your case you could not notice the difference cause the parent was wrapping so close the child element that every click seemed to target the same selector. Adding some padding to the parent (like in my demo) makes the difference more clear.

Upvotes: 3

Cosmitar
Cosmitar

Reputation: 1084

The difference is in which object you are attaching the listener for click event. For case:

$('#foo').on('click', function(){
  $(this).find('.bar').css('background-color', 'yellow');
})

You are attaching the listener to the #foo object.

For case:

$('#foo_two .bar_two').on('click', function(){
  $(this).css('background-color', 'red');
})

You are attaching the listener to the #foo_two .bar_two object

I adjust your fiddle to show the difference. Green label changes when you click de div element but orange label changes when you click the p element

http://jsfiddle.net/0qcssuue/3/

Upvotes: 1

Related Questions