views:

41

answers:

2

In the example of jQuery's find()
(the doc is at http://api.jquery.com/find/)

I wonder why we need it, because, is

$('li.item-ii').find('li')

the same as

$('li.item-ii li')

essentially, all the <li> elements inside the <li> element that has the class item-ii

Similarly

$('#id1').find(".class1 #id2")

is the same as

$('#id1 .class1 #id2")

?

Update: if they are the same, why do we need find() ? is it because mainly when we need to further select some elements when given another element in a variable, so we can do elementFoo.find("...")?

+4  A: 

Yes, these are equivalent. The result is the same, it's called the descendant selector. Their utility differs a little bit (e.g. using .end(), .andSelf(), etc), but for just selecting elements, you're finding the same set.

For kicks, you can also do this:

$('li', 'li.item-ii')

For your edit: Why do we need it? Sometimes you're not coming from a selector, quick example:

$(this).find('.childElementClass')

There are many times you need to find something relatively, not from a known selector (could be a DOM element, this, an iframe document, etc). There are many other traversal functions for this as well.

Nick Craver
Well isn't that the same as $('.childElementClass', this) =P
Louis
@Louis - Yup, `$(selector, context)` is just `context.find(selector)` internally, actually `$(selector)` is still `$(document).find(selector)`, just eliminating a few lines of code calling the `.find()` directly is all.
Nick Craver
+1 Great answer of course :) I do worry that you gave such a poor example in your "for kicks" item. There is no speed improvements by doing it that way unless the second parameter is a DOM elements like `this` in a callback or loop. Otherwise, jQuery is doing the same amount of work (or more?) to do the same lookup. I realize it was for kicks, but its a bad use case nonetheless.
Doug Neiner
+1  A: 

They are basically identical yes. But if for example you already have your DOM element it can be very useful. Say for example you've bound to a click event on a div and want to hide all spans in the div. It's as simple as $(this).find('span').hide() whereas it would be quite difficult to do with the other syntax.

Also it can make sense sometimes to store your $('li.item-ii') result in a variable because you want to run more than 1 query (Say you want to first find the li's under it, but also want to find the spans in there too). This syntax allows you to not duplicate the selector every time you want to access another child element which is significantly better for maintainability (I believe there may also be a performance benefit also in not re-running the base selector, but it probably depends on the use-case).

So in short, it's two methods of doing the same thing yes, but they're more suitable than one another under different circumstances.

Tim Schneider