[Rails-spinoffs] Re: Get Elements Within ID

Eric Anderson eric at afaik.us
Mon Jul 3 13:47:23 GMT 2006


Andrew Kaspick wrote:
> I would have to think that $('abc').getElementsByTagName('span') would
> run faster than making use of $$.
> 
> $$ would have to evaulate the entire document.  Starting at a known
> parent should be much much faster.

> On 7/3/06, Maninder, Singh 
>>  $$('div#abc span').each(function(el) {
>>    //do something
>>  });


Actually there should not be any noticeable performance difference. The 
only real difference between:

$$('div#abc span')

and

$('abc').getElementsByTagName('span')

is parsing the CSS selector and building a match expression. But the 
cost of that is fairly low (two regular expression and few statements 
that are only executed once).

Otherwise it will execute the statements above basically the same (find 
then "abc" element using $() then find all "span" tags that are below 
that element in the DOM hierarchy by using document.getElementsByTagName).

It is informative to take a look at

http://dev.rubyonrails.org/browser/spinoffs/prototype/src/selector.js?format=txt

Look at the "findElements" method and you can see it does the following:

1. Tries to find the element using $() if an id is given
2. Gets a list of all elements in scope (determined by the previous CSS 
selector fragment) and filters that list down by tag name if the tag 
name is given.
3. Once it has filtered the list down as much as possible with standard 
DOM search methods, only then will it do a linear search of the elements 
to ensure that the id, class and tag name match the CSS selector.

It is quite efficient although there is still room for improvement when 
finding elements that match a class name. I would only use something 
other than $$() if I really had some performance constraint.

Eric



More information about the Rails-spinoffs mailing list