As we know how selector engines will require the ability to recurse (finding descendant elements) and merge the results together.
However our implementation is too simple, note that we end up receiving two spans in our results instead of just one. Because of this we need to introduce an additional check to make sure the returned array of elements only contains unique results. Most top down selector implementations include some method for enforcing this uniqueness.
Unfortunately there is no simple way to determine the uniqueness of a DOM element. We’re forced to go through and assign temporary IDs to the elements so that we can verify if we’ve already encountered them.
<div id="test">
<b>Hello</b>, I'm a ninja!
</div>
<div id="test2"></div>
(function(){
var run = 0;
this.unique = function( array ) {
var ret = [];
run++;
for ( var i = 0, length = array.length; i < length; i++ ) {
var elem = array[ i ];
if ( elem.uniqueID !== run ) {
elem.uniqueID = run;
ret.push( array[ i ] );
}
}
return ret;
};
})();
window.onload = function(){
var divs = unique( document.getElementsByTagName("div") );
assert( divs.length === 2, "No duplicates removed." );
var body = unique( [document.body, document.body] );
assert( body.length === 1, "body duplicate removed." );
};
This unique method adds an extra property to all the elements in the array - marking them as having been visited. By the time a complete run through is finished only unique elements will be left in the resulting array. Variations of this technique can be found in all libraries.