![](https://codelido.com/assets/files/2023-03-06/1678107037-280330-image.png)
A top down engine works by parsing a CSS selector from left-to-right, matching elements in a document as it goes, working relatively for each additional selector segment. It can be found in most modern JavaScript libraries and is, generally, the preferred means of finding elements on a page.
For example, given the selector “div span” a top down-style engine will find all div elements in the page then, for each div, find all spans within the div.
There are two things to take into consideration when developing a selector engine: The results should be in document order (the order in which they’ve been defined) and the results should be unique (no duplicate elements returned). Because of these gotchas developing a top down engine can be quite tricky.
Take the following piece of markup into consideration, as if we were trying to implement our “div span” selector.
A simple top down selector engine:
<div>
<div>
<span>Span</span>
</div>
</div>
window.onload = function(){
function find(selector, root){
root = root || document;
var parts = selector.split(""),
query = parts[0],
rest = parts.slice(1).join(""),
elems = root.getElementsByTagName( query ),
results = [];
for ( var i = 0; i < elems.length; i++ ) {
if ( rest ) {
results = results.concat( find(rest, elems[i]) );
} else {
results.push( elems[i] );
}
}
return results;
}
var divs = find("div");
assert( divs.length === 2, "Correct number of divs found." );
var divs = find("div", document.body);
assert( divs.length === 2, "Correct number of divs found in body." );
var divs = find("body div");
assert( divs.length === 2, "Correct number of divs found in body." );
var spans = find("div span");
assert( spans.length === 2, "A duplicate span was found." );
};
In the above listing we implement a simple top down selector engine (one that is only capable of finding elements by tag name). The engine breaks down into a few parts: Parsing the selector, finding the elements, filtering, and recursing and merging the results.