Think Right to left with Jquery
by Guna[ Edit ] 2011-02-08 13:29:58
As English speakers, our minds are geared toward interpreting data and text from left-to-right. However, as it turns out, many of the modern JavaScript selector engines (jQuery, YUI 3, NWMatcher), and the native querySelectorAll, parse selector strings from right to left.
Consider the following selector:
div id="box"
p id="elem" Hello
div
// The Test
//1 .
$('#box p');
// 2.
$('#box').find('p');
using find() or children() is roughly 20-30% faster, depending upon the browser.
Though some — generally older — selector engines will first query the DOM for the element with a class of box, and then move on to finding any p tags which are children, jQuery works in reverse. It begins by querying the DOM for all paragraph tags on the page, and then works it way up the parent nodes and searches for .box.