getElementsBy(*) are some common DOM API to find elements matching a certain selector. They are often used to navigate/find elements on a DOM tree. In this blog, we’ll learn how to possible recreate them using recursive DOM transversal.
We’ll consider the following HTML document for all the below problems for simplicity:
Implement a getElementsByTagName function which takes a rootElement and a tagSelector, and finds and returns all elements matching the tagName. You can ignore the root element.
Implement a getElementsByClassName function which takes a rootElement and classNames, and finds and returns all elements matching the classNames (can be more than one). You can ignore the root element.
In this implementation, the utility function getFormattedClassNames, may or may not be needed based on how className field is passed. In general there might be few cases you need to handle:
Whether only you need to match one or more classNames?
Whethere the classNames passed contains duplicates, whitespaces etc?
My implementation covers the above cases this way, but there maybe be other cases which we might need to cover depending upon the interview. One example can be, lowercase and uppercase classnames 😅
Implement a getElementsByCustomDataAttribute function which takes a rootElement, a custom attribute name and value, and finds and returns all elements contain the custom attribute name and value. You can ignore the root element.
There may be further variations of this to check for a list of data attributes, a particular style attribute like color, fontSize etc.
The possibilities here are endless, but the core transversal remains same with only the filter/matching logic changes.
Example, if we were to check for a particular style attribute like color, we could simply do:
In this implementation, we need to find elements which follow a given classname hierarchy on DOM, i.e, fruits>apple>ripe Hierarchy means finding all elements will classname ripe which are direct children of elements with classname apple and so on..