Skip to the code
cf.
+10 XP

#701 Find Every Element of One Tag

easy

A lazy-loading script needs every img on a page, and a link checker needs every a. Both work like getElementsByTagName.

Write byTag(root, tag) that returns the ids of all elements whose tag equals tag, in document order (parent before children, children in order). root itself counts if it matches. Elements are objects with tag, id, and optional children. If root is null or nothing matches, return an empty array.

Example 1

Input: root = {"tag":"nav","id":"n","children":[{"tag":"a","id":"n1"},{"tag":"a","id":"n2"},{"tag":"button","id":"n3"},{"tag":"a","id":"n4"}]}, tag = "a"
Output: ["n1","n2","n4"]

Three links, in the order they appear; the button is skipped.

Example 2

Input: root = {"tag":"body","id":"root","children":[{"tag":"header","id":"top","children":[{"tag":"h1","id":"title"}]},{"tag":"main","id":"content","children":[{"tag":"p","id":"intro"},{"tag":"ul","id":"list","children":[{"tag":"li","id":"a"},{"tag":"li","id":"b"}]}]}]}, tag = "li"
Output: ["a","b"]

Both list items, inside ul#list.

Constraints

  • The tree has 0 to 10^4 elements.
  • Tags are lowercase strings.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).