css selectors vs jquery traversal

2020-02-09 11:23发布

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.

2条回答
Evening l夕情丶
2楼-- · 2020-02-09 11:33

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()

查看更多
淡お忘
3楼-- · 2020-02-09 11:40

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.

查看更多
登录 后发表回答