The task is to get all the tag names in a DOM tree.
The boilerplate code
function getTags(tree) {
// your code here
}
If a tag name appears multiple times, it should be stored once. Using a set ensures uniqueness
const tags = new Set();
Traverse through the DOM tree recursively. First, guard against null or undefined
function traverse(node) {
if (!node) return;
Only element nodes have tag names. Tag names are always returned in uppercase, so they should be converted to lowercase.
if (node.tagName) {
tags.add(node.tagName.toLowerCase());
}
Each child element is visited recursively also
if (node.children) {
for (const child of node.children) {
traverse(child);
}
}
Every element in the tree is visited exactly once. Convert Set to Array and sort
return Array.from(tags).sort();
Sorting guarantees a predictable output. The final code
function getTags(tree) {
// your code here
const tags = new Set();
function traverse(node) {
if(!node) return;
if(node.tagName) {
tags.add(node.tagName.toLowerCase());
}
if(node.children) {
for(const child of node.children) {
traverse(child)
}
}
}
traverse(tree);
return Array.from(tags).sort();
}
That's all folks!
Top comments (0)