user2444542
user2444542

Reputation:

Jquery traversing and using selectors

I'm reading a book and they show a couple of examples of how to select elements on the DOM, but they advise to always use Jquery trasversing methods over the selectors, for example if you have a list inside a div instead of using

$("#myList > li")

You should use

$("#myList").children("li")

Most of the time I use the first over the latter, the author says the 2nd is prefered and more efficient but he does not address why, can anyone explain the reason behind this?

Upvotes: 5

Views: 115

Answers (1)

elclanrs
elclanrs

Reputation: 94131

I think the difference in performance in that particular case comes down to this:

document.querySelectorAll('#myList > li');
// VS
document.getElementById('myList').children;

And the performance test here: http://jsperf.com/ae-d2-56-2a-e2-36-a3-d3-52-74

jQuery might check to see if it's a li given the selector but that's still going to be faster than querySelectorAll or Sizzle.

Upvotes: 5

Related Questions