I’ve been playing around with several options, including jQuery filter, and my own recursive descent functions, and I’m not impressed with my results so far.
I’m going to dive in and see how efficient I can make my code; I bet someone else has done this, though, and done a good job.
So, what’s the most efficient way for me to search through a dom tree? Say, for example, that I want to find all of the elements which have a src property which matches (/.*google.*/)
Something like this.
or
See this test case (looks like by stats the first selector is 14 times as fast as the second, with exactly the same selector)
http://jsperf.com/test-selectorfidd123
Want to know why? jQuery has to loop through each element for each element it can find if you use the second selector. If you use the first, jQuery will look foor the
rootnode which it will use a highest node of the hyarchie. And will not loop through all the otherDIVScus it’s not necesarry.A few months ago I did some more tests. If you use selectors which are able to run within CSS. jQuery is able to use
querySelectorfrom the native library. But if you use special selectors like:selectedor:nth-childthen jQuery has to use Javascript to loop through these elements. At that case it is better do something like: (where jQuery will usequerySelectorfor the first part and JS for the.findInformation:
Attribute contains selector
Selector API