Skip to content

Commit

Permalink
💥 NEW: Add function to get all DOM tags recursively and iteratively
Browse files Browse the repository at this point in the history
  • Loading branch information
Shaban-Eissa committed Jun 7, 2024
1 parent 50fea98 commit d251d79
Showing 1 changed file with 152 additions and 0 deletions.
152 changes: 152 additions & 0 deletions 68.get-DOM-tags.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# 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 `Element`s.

### Implementation

Recursive DFS:

```js
/**
* @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:

```js
/**
* @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:

```js
/**
* @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

```js
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"]
```

0 comments on commit d251d79

Please sign in to comment.