-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind-class.js
More file actions
69 lines (64 loc) · 1.46 KB
/
find-class.js
File metadata and controls
69 lines (64 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Input is a JSON structure of DOM Elements. We need to implement to get all the ids with className 'baz'
* */
var input = {
tree: {
tagName: "div",
attributes: {
id: "0",
class: "foo bar baz"
},
childNodes: [
{
tagName: "span",
attributes: {
id: "1",
class: "baz bar"
},
childNodes: []
},
{
tagName: "p",
attributes: {
id: "2",
class: "baz"
},
childNodes: [
{
tagName: "span",
attributes: {
id: "3",
class: "baz"
},
childNodes: []
}
]
}
]
}
};
// Output: [0, 1];
let hasRootClassName = (root, className) => {
var attributes = root.attributes;
return attributes.class.split(" ").includes(className) ? attributes.id : null;
};
let traverseChild = (nodes, className) => {
let idToPass = [];
nodes.forEach(node => {
idToPass.push(hasRootClassName(node, className));
if (node.childNodes.length) {
idToPass.push(...traverseChild(node.childNodes, className));
}
});
return idToPass;
};
let findClassName = function(className) {
let ids = [];
if (!Object.keys(input).length) {
console.log("Dom is empty");
}
var root = input.tree;
ids.push(hasRootClassName(root, className));
ids.push(...traverseChild(root.childNodes, className));
return ids.filter(id => id).sort();
};