9

With jquery there seem to be two ways of finding a list item within an unordered list within the DOM.

$("ul>li");

and

$("ul").find("li"); 

Is there a reason why the latter might be more preferable? It seems like one would need more code to get the same result.

5
  • 1
    find selects all the matching descendant elements, > is a direct child selector. This shows that you haven't read the jQuery documentation. Commented Apr 30, 2013 at 20:28
  • You are wrong. $("ul>li") will find only first li for any ul, where $("ul").find("li") will find all li in each ul. You mean in first case: $("ul li") right? Commented Apr 30, 2013 at 20:28
  • It depends. In most cases trying to decide which version to use based on performance is pre-mature optimization, so in most cases it makes more sense to choose the one that is more maintainable and/or easy to read/understand rather than worrying about which one is faster. Commented Apr 30, 2013 at 20:29
  • 1
    @WooCaSh No, it will find all direct children of every ul that is a li. However, yes, $("ul li") would be the correct comparison. Commented Apr 30, 2013 at 20:30
  • @KevinB right. It find only all li on first level, where find on each level under ul. Commented Apr 30, 2013 at 20:32

2 Answers 2

12

Yup. Speed. .find() will win every time. And speed of processing is tantamount!

jsPerf speed test to show what I mean

Although .find() will get everything that is a subordinate (children, children of children, children of children of children, etc), and > is a direct child selector. Its a better apples-to-apples to compare either of the following:

  • $('ul li') vs $('ul').find('li')
  • $('ul > li') vs $('ul').children('li')

Although if you do .find('li') it'll still be the fastest way to do it, even faster than .children('li').

updated jsPerf to include .children()

Sign up to request clarification or add additional context in comments.

Comments

1

1) they're not the same, the second form would be equivalent to $("ul li"); and the first one is equivalent to $("ul").children("li")

2) If you're using the second form, you simplify jQuery's parsing task. But it makes your code less simple so I wouldn't recommend it unless you proved speed is very relevant in your case. This being said you usually have more code with for example some element caching, or some other traversing functions, justifying the use of find.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.