views:

99

answers:

3
$.prev("div.a").find('.b').

$.prev("div.a .b").

One works and the other does not. What's the difference?

A: 

MAYBE there is a rule don't mess tag with class/ids... or maybe not... :) try ("div.a div.b") and (".a .b") (currentrly i can't)

Rin
A: 

find() does not search the selected elements, only their descendants ... so if the .b class is on the div.a element, you won't find it.

Find will find:

<div class="a">
  <div class="b">

But not:

<div class="a b">

For more: http://docs.jquery.com/Traversing/find

Toby Hede
@stuart: yep - @toby: you may have missed the space in the second example.
nickf
you could do $('div[class=a][class=b]')
Vince
@Vince: no need to use attribute selectors, `$('div.a.b')` will do the trick
Marve
+5  A: 

Well, the selector works, it just doesn't give you what you want:

According to jQuery Docs .prev([expr]):

Get a set of elements containing the unique previous siblings of each of the matched set of elements. Use an optional expression to filter the matched set. Only the immediately previous sibling is returned, not all previous siblings.

This means: $(elem).prev("div.a").find('.b') is looking for any previous sibling in the DOM Tree that is a div.a and returning the first - then search within that element using .find() for a .b

Whereas: $(elem).prev("div.a .b") is looking for any previous sibling that is a div.a .b and returning the first.

They are not equivalent and therefore return different results.

gnarf