How Is Document.querySelector Implemented?

- 1 answer

I suppose the answer to this question depends on what browser you are using, but I guess that just makes it all the more interesting.

I'm wondering how the querySelector() method is actually implemented. Similarly, I'm curious about querySelectorAll() and other methods like getElementById() and getElementByClassName() etc.

Is it a depth first search, breadth first search, or does it utilize some auxiliary data structure, like a global hash table to act as a registry?



All the information you asked for is in the links you provided:

querySelector: Returns the first element within the document (using depth-first pre-order traversal of the document's nodes|by first element in document markup and iterating through sequential nodes by order of amount of child nodes) that matches the specified group of selectors.

querySelectorAll: Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.

getElementById: Returns a reference to the element by its ID; the ID is a string which can be used to identify the element; it can be established using the id attribute in HTML, or from script.

as an ID should be unique - there's no question of order

getElementsByClassName: Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.