jQuery is quite multifaceted when it comes to selecting certain DOM elements. Today it came to my attention that the two ways of getting the same elements may yield different speed:
$("selector1").find("selector2").find("selector3")
and
$("selector1 selector2 selector3")
(where selectorX
can be ID or class or anything else)
Both produce the same set of elements but are there any speed differences? How does jQuery actually traverse DOM? This is especially important in the second case: does it go from selector1 to selector3 or the other way around?
Anybody measured the difference between the two?
Using a single $('...')
is about twice as fast as chaining $.find()
s for me in Chrome. This JSPerf Benchmark will give you a good idea of other browsers as well once some more people test it.
Time it yourself and find out!
console.time("Selector 1")
$("selector1").find("selector2").find("selelector3");
console.timeEnd("Selector 1")
console.time("Selector 2")
$("selector1 selector2 selector3");
console.timeEnd("Selector 2")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With