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
|
define(function () {
const reduce = (elements, fn, initialValue) => {
return Array.prototype.reduce.call(elements, fn, initialValue);
}
const forEach = (elements, fn) => {
Array.prototype.forEach.call(elements, fn);
}
const map = (elements, fn) => {
return Array.prototype.map.call(elements, fn);
}
const replace = (toReplace, replacement) => {
var parentElement = toReplace.parentElement
if (parentElement) {
parentElement.replaceChild(replacement, toReplace);
}
}
const matches = (element, selector) => {
var m = element.matches
|| Element.prototype.matchesSelector
|| Element.prototype.mozMatchesSelector
|| Element.prototype.msMatchesSelector
|| Element.prototype.oMatchesSelector
|| Element.prototype.webkitMatchesSelector;
return m.call(element, selector);
}
const closest = (element, selector) => {
while (element) {
if (matches(element, selector)) {
return element;
} else {
element = element.parentElement;
}
}
return null;
}
const isFunction = (input) => (typeof input === "function");
const dispatchEvent = (eventName, data) => {
let event;
if (window.CustomEvent && isFunction(window.CustomEvent)) {
event = new CustomEvent(eventName, { detail: data, cancelable: true, bubbles: false });
} else {
event = document.createEvent('CustomEvent');
event.initCustomEvent(eventName, false, true, data);
}
return window.document.dispatchEvent(event);
}
const parseHtml = (htmlString) => {
const c = document.createElement('div');
c.innerHTML = htmlString.trim();
return c.firstChild;
}
return {
dispatchEvent,
closest,
matches,
reduce,
map,
forEach,
replace,
parseHtml
};
});
|