-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdom-tools.js
93 lines (81 loc) · 2.58 KB
/
dom-tools.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
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
88
89
90
91
92
93
export function removeChildren(element) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
export function removeElement(element) {
element.parentNode.removeChild(element);
}
export function replaceElement(oldElement, newElement) {
oldElement.parentNode.replaceChild(newElement, oldElement);
}
export function insertAtCursor(element, value) {
if (element.tagName == "TEXTAREA") {
const startPosition = element.selectionStart;
const endPosition = element.selectionEnd;
element.value = element.value.substring(0, startPosition) + value + element.value.substring(endPosition, element.value.length);
//move cursor
const newIndex = startPosition + value.length;
element.setSelectionRange(newIndex, newIndex);
}
}
export function fireEvent(element, eventName, bubbles = true, cancelable = true) {
const event = document.createEvent("HTMLEvents");
event.initEvent(eventName, bubbles, cancelable); // event type,bubbling,cancelable
return element.dispatchEvent(event);
}
export function createOptionList(list, valueFunc = x => x, displayFunc = y => y) {
const docFrag = document.createDocumentFragment();
for (let i = 0; i < list.length; i++) {
const option = document.createElement("option");
option.value = valueFunc(list[i]);
option.textContent = displayFunc(list[i]);
docFrag.appendChild(option);
}
return docFrag;
}
export function getMatchingCss(element) {
const sheets = document.styleSheets;
const matches = [];
element.matches = element.matches || element.msMatchesSelector;
for (let i in sheets) {
const rules = sheets[i].rules || sheets[i].cssRules;
for (let rule in rules) {
if (element.matches(rules[rule].selectorText)) {
matches.push(rules[rule].cssText);
}
}
}
return matches;
}
export function cloneParentNodeTree(element) {
const nodes = [];
while (element.parentNode) {
nodes.unshift(element.cloneNode(false));
element = element.parentNode;
}
const root = nodes[0];
for (let i = 1; i < nodes.length; i++) {
nodes[i - 1].appendChild(nodes[i]);
}
return {
root,
element: nodes[nodes.length - 1]
};
}
export function copy(element) {
const hasSelection = document.queryCommandEnabled('copy');
if (!hasSelection) {
console.log('copy not enabled');
}
element.select();
try {
document.execCommand('copy');
} catch (err) {
console.log('execCommand Error', err);
}
}
export function tableToArray(table){
return [...table.querySelectorAll("tr")].map(row =>
[...row.querySelectorAll("td")].map(td => td.textContent));
}