-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
87 lines (75 loc) · 2.09 KB
/
script.js
File metadata and controls
87 lines (75 loc) · 2.09 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// The regular expressions used to find each type of future selector
const REGEX = {
element: /<(\w*?)[ >]/g,
class: /class="(.*?)"/g,
id: /id="(.*?)"/g,
};
// A list of HTML elements that cannot be styled with CSS and therefore should not be included in the output
const EXCLUDED_TAGS = [
"base",
"head",
"link",
"meta",
"style",
"title",
"canvas",
"script",
"noscript",
];
// Select the button on the page and add a listener for a click event
const btn = document.querySelector("#extractor");
btn.addEventListener("click", updateOutput);
function updateOutput() {
const outputBox = document.querySelector("#output");
const inputBox = document.querySelector("#input");
const checkedOptions = document.querySelectorAll("input:checked");
let options = [];
checkedOptions.forEach((checkbox) => {
options.push(checkbox.getAttribute("id"));
});
if (options.length === 0) {
return alert("You must select an option!");
}
const foundSelectors = parseInput(inputBox.value, options);
outputBox.value = "";
outputBox.value = generateOutput(foundSelectors);
}
function parseInput(rawHtml, options) {
const allSelectors = [];
options.forEach((option) => {
allSelectors.push(...extractSelectors(rawHtml, option));
});
const uniqueSelectors = [...new Set(allSelectors)];
return uniqueSelectors;
}
function generateOutput(selectorsArr) {
let stringOutput = "";
selectorsArr.forEach((selector) => {
stringOutput += `${selector} { }
`;
});
return stringOutput;
}
function extractSelectors(input, type) {
const matchedSelectors = [];
const regex = REGEX[type];
const allMatches = [...input.matchAll(regex)];
allMatches.forEach(([, result]) => {
const match = result.split(" ");
if (match.length === 1) {
matchedSelectors.push(
...match.map((keyword) => {
return type === "class"
? `.${keyword}`
: type === "id"
? `#${keyword}`
: !EXCLUDED_TAGS.includes(keyword)
? `${keyword}`
: "";
})
);
} else {
}
});
return matchedSelectors;
}