-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdom.js
69 lines (54 loc) · 1.58 KB
/
dom.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
/**
* DOM utils.
*/
// Query selectors
export function $(selector, node = document) {
return node.querySelector(selector);
}
export function $$(selector, node = document) {
return [].slice.call(node.querySelectorAll(selector));
}
// Element manipulation
export function hideEl(...elements) {
elements.forEach(e => e.classList.add('hidden'));
}
export function showEl(...elements) {
elements.forEach(e => e.classList.remove('hidden'));
}
export function toggleEl(...elements) {
elements.forEach(el => el.classList.toggle('hidden'));
}
export function clearEl(...elements) {
elements.forEach(el => { while (el.firstChild) el.removeChild(el.firstChild); });
}
export function removeEl(...elements) {
elements.forEach(el => el.parentNode.removeChild(el));
}
export function makeEl(tag, attr = {}) {
const el = document.createElement(tag);
for (const prop in attr) el[prop] = attr[prop];
return el;
}
export function whenReady(callback) {
if (document.readyState !== 'loading') callback();
else document.addEventListener('DOMContentLoaded', callback);
}
export function once(node, type, listener) {
function wrapper() {
node.removeEventListener(type, wrapper);
return listener.apply(this, arguments);
}
node.addEventListener(type, wrapper);
}
// HTML manipulation
export function toEl(str) {
const div = document.createElement('div');
div.innerHTML = str;
return div.children[0];
}
export function escapeHtml(html) {
return html.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/"/g, '"');
}