I use Sizzle (the selector engine in jQuery). Sizzle returns an array of DOM elements. My function returns the first item if there’s only one, unless I specify using the arr attribute that I want an array even if there’s only one item. Makes it easy to do stuff like this, knowing I’m working with an actual DOM element rather than some other object:
That makes sense. I was tempted to go down the route of using sizzle or sly etc. Would have been the sensible thing to do. Mine has a get method attached which does return an array. I could add the length test to account for single nodes though.
So, for CSS it’s clear that as we KNOW it parses from right to left, any extra step will demand more processing.
Btw, i know this has been widely debated, but right-to-left for CSS seems counter intuitive for developers.
Come on, who ever replaced “#div a” by adding a class to every single link in DIV ? seriously …
Regarding JS, there doens’t seem to be a clear consensus. Looks like there may be a difference between the selector engines … (btw jquery is not the only one out there).
There are two approaches in Javascript(among others) which is bottom up or top down.
Top down works left to right through the selector, and the bottom up right to left working it’s way up through parent nodes etc.
Top down is quicker and would seem like the easy choice, but there is a down side and this is covered in Javascript ninja.
Example.
<div>
<div>
<span></span>
<div>
</div>
Selector 'div span'.
The top down(left to right) firsts look for div tags and come up with two elements.
Those found elements will then each be passed back to the search but this time as the root of the next search. (Does that make sense?)
This time round the search will find a span tag on each of the found div elements(root elements).
The end result when all is returned is that you end up wrongly finding two identical span tags.
One way around it is to add temporary unique identifiers to the found elements, and that way filter out duplicates.
Another way is to go with the bottom up(right to left) approach. I don’t know but this might expain css’s logic.
Cheers
RLM