If I have already got, in my variable $a_div, a jQuery object for the DIV in the following markup and I want to find the Ps
<div id="a">
...
<p>...</p>
...
</div>
Is there a significant performance difference between these ways to select the P elements in the DIV?
$('#a p')
$('p', $a_div)
$a_div.find('p')
And if so, do you know why?
This sort of thing is usually browser dependent, but I’d use the 3rd one.
First one, browsers with
querySelectorAllwill make use of it, so performance should be good.In browsers that don’t support
qsa, I think Sizzle finds allpelements on the page, and traverses their ancestors to see if there’s a#aelement.I wouldn’t use the second one at all, because it gets changed to the third one in the background.
Whether via
querySelectorAllorgetElementsByTagName, you’re starting from a known point in the DOM, and only searching within it, so I’d bet that this will generally be fastest.