Collect descendants matching tag names up to a max depth
An accessibility linter scans a page section by section. One rule wants every link and button in a card, another only wants the headings that sit directly in a section (not the ones nested inside widgets). Both need a tag search that can match several tag names at once and stop at a given depth.
Implement collectTags(root, tagNames, maxDepth). It returns an array of the elements inside root whose tag name matches.
collectTags(root, tagNames, maxDepth = Infinity) // => Element[]
root is an Element or a DocumentFragment, attached to the document or not. Only its descendants are searched; root itself is never in the result.tagNames is a tag name ('a') or an array of them (['a', 'button']). An element matches if its tag name equals any of them.'LI', 'li' and 'Li' are the same. This includes mixed-case SVG tags such as linearGradient.'*' matches every element.root: its children are at depth 1, their children at depth 2, and so on. Only elements at depth maxDepth or less are returned. maxDepth defaults to Infinity; 0 returns [].tagNames array returns [].getElementsByTagName, querySelector, querySelectorAll, or a TreeWalker/NodeIterator.<section id="card">
<h2 id="title">Plans</h2>
<ul id="list">
<li id="basic"><a id="basic-link" href="#">Basic</a></li>
<li id="pro">Pro <button id="buy">Buy</button></li>
</ul>
<p id="note">See <a id="terms" href="#">terms</a></p>
</section>
const card = document.getElementById('card');
const ids = (elements) => elements.map((element) => element.id);
ids(collectTags(card, 'a')); // => ['basic-link', 'terms']
ids(collectTags(card, ['button', 'A'])); // => ['basic-link', 'buy', 'terms']
ids(collectTags(card, '*', 1)); // => ['title', 'list', 'note']
ids(collectTags(card, 'a', 2)); // => ['terms']
ids(collectTags(card, 'section')); // => [] (root is not included)
ids(collectTags(card, 'table')); // => []