开发者

In jQuery, is $('li.item-ii').find('li') the same as $('li.item-ii li')?

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("...")?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜