-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
50 lines (45 loc) · 1.24 KB
/
index.js
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
const myQuerySelector = (selector) => {
selector = selector.trim().split(" ");
const subSelectors = [];
for (let i = 1; i < selector.length; i++) {
const element = selector[i];
subSelectors.push(element);
}
return myActualQuerySelector(document.body, selector[0], subSelectors, []);
};
const myActualQuerySelector = (
element,
mainSelector,
subSelectors,
elements
) => {
for (let i = 0; i < subSelectors.length; i++) {
const subSelector = subSelectors[i];
if (element.tagName.toLowerCase() === subSelector) {
elements.push(element);
}
}
if (!element.children.length) return elements;
for (let i = 0; i < element.children.length; i++) {
const child = element.children[i];
if (isChildOfMainSelector(child, mainSelector)) {
myActualQuerySelector(
child,
mainSelector,
subSelectors,
elements
);
}
}
return elements;
};
const isChildOfMainSelector = (child, mainSelector) => {
while(child.tagName.toLowerCase() !== 'body') {
if (child.tagName.toLowerCase() === mainSelector) {
return true;
}
child = child.parentElement;
}
return false;
}
console.log(myQuerySelector("div p b ul"));