Aarmora
Aarmora

Reputation: 1153

JQuery Selectors for siblings/children/parent

So I feel like my title is almost ambiguous but the truth is I'm not even sure how to clarify...hence the question.

Html

<tr>  
  <div class="thisis(this)inmyexample"></div>
  <div class="stuff">
    <div class="foo"></div>
  </div>
</tr>

My question is on the difference in selectors. Let's assume that .stuff is a sibling of $(this) If I use this:

$(this).closest('tr').find('.stuff .foo')

Now, I realize this isn't efficient coding but it's just as an easy example. With it, I will find all classes of .foo that are children of .stuff.

If I use this:

$(this).siblings('.stuff .foo')

I won't find anything. This is my inexperience with jquery talking, probably, but why wouldn't that kind of selector (what do you call a selector that uses a space or has both together, like '.stuff.foo'?) work with something like .siblings? My expectation is that it would find all siblings with the class of .stuff and then find all children of .stuff with a class of .foo. Is it not working because siblings/children/parent is looking for just the sibling/parent/child and won't look past that?

I know I can use this:

$(this).siblings('.stuff').children('.foo')

and I achieve my goal. I'm just curious why my above selector (if that's what it's properly called) wouldn't work.

Thanks in advance!

Upvotes: 3

Views: 140

Answers (1)

Vlad
Vlad

Reputation: 555

you answered your own question, you won't find anything with $(this).siblings('.stuff .foo') because .foo is not a sibling of $(this), it's sort of a 'grandchild'.using that selector, it will look for .foo siblings that have .stuff parents, whereas you have $(this), a sibling of .stuff and .foo, a child of .stuff, and NOT a sibling of $(this).

Upvotes: 2

Related Questions