Skip to content

Latest commit

 

History

History
152 lines (118 loc) · 2.76 KB

68.get-DOM-tags.md

File metadata and controls

152 lines (118 loc) · 2.76 KB

68. get DOM tags

Problem

https://bigfrontend.dev/problem/get-DOM-tags

Problem Description

Given a DOM tree, please return all the tag names it has.

Your function should return a unique array of tags names in lowercase, order doesn't matter.

Understanding the problem

We are given a DOM tree and we are asked to write a function that returns all the unique tag names in it in an array. The tag names should be returned in lowercase, and we can return them in any order.

Approach

We could traverse the DOM tree using either DFS or BFS to get all of the tag names. To store only the unique tag names, we could make use of a Set, since a Set cannot have duplicate values.

Because only an Element has the tag, as we traverse the DOM tree, we need to use Element.children rather than Node.childNodes to get only the child Elements.

Implementation

Recursive DFS:

/**
 * @param {HTMLElement} tree
 * @return {string[]}
 */
function getTags(tree) {
  const tagNames = new Set();

  dfs(tree, tagNames);
  return [...tagNames];
}

function dfs(el, tagNames) {
  const tagName = el.tagName.toLowerCase();
  tagNames.add(tagName);

  for (const child of el.children) {
    dfs(child, tagNames);
  }
}

Iterative DFS:

/**
 * @param {HTMLElement} tree
 * @return {string[]}
 */
function getTags(tree) {
  const tagNames = new Set();
  const stack = [tree];

  while (stack.length > 0) {
    const el = stack.pop();
    const tagName = el.tagName.toLowerCase();
    tagNames.add(tagName);

    stack.push(...el.children);
  }

  return [...tagNames];
}

Iterative BFS:

/**
 * @param {HTMLElement} tree
 * @return {string[]}
 */
function getTags(tree) {
  const tagNames = new Set();
  // Assume we have a Queue data structure implemented.
  const queue = [tree];

  while (queue.length > 0) {
    const el = queue.shift();
    const tagName = el.tagName.toLowerCase();
    tagNames.add(tagName);

    queue.push(...el.children);
  }

  return [...tagNames];
}

Usage

const DOM = {
  tagName: "div",
  children: [
    {
      tagName: "h1",
      children: [
        {
          tagName: "span",
          children: [
            {
              tagName: "a",
              children: [
                {
                  tagName: "span",
                  children: [],
                },
              ],
            },
          ],
        },
      ],
    },

    {
      tagName: "p",
      children: [
        {
          tagName: "span",
          children: [],
        },
        {
          tagName: "a",
          children: [
            {
              tagName: "span",
              children: [],
            },
          ],
        },
      ],
    },
  ],
};

console.log(getTags(DOM)); // ["div", "h1", "span", "a", "p"]