forked from docsifyjs/docsify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdom.js
83 lines (69 loc) · 1.81 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { isFn } from '../util/core'
const cacheNode = {}
/**
* Get Node
* @param {String|Element} el
* @param {Boolean} noCache
* @return {Element}
*/
export function getNode (el, noCache = false) {
if (typeof el === 'string') {
if (typeof window.Vue !== 'undefined') {
return find(el)
}
el = noCache ? find(el) : (cacheNode[el] || (cacheNode[el] = find(el)))
}
return el
}
export const $ = document
export const body = $.body
export const head = $.head
/**
* Find element
* @example
* find('nav') => document.querySelector('nav')
* find(nav, 'a') => nav.querySelector('a')
*/
export function find (el, node) {
return node ? el.querySelector(node) : $.querySelector(el)
}
/**
* Find all elements
* @example
* findAll('a') => [].slice.call(document.querySelectorAll('a'))
* findAll(nav, 'a') => [].slice.call(nav.querySelectorAll('a'))
*/
export function findAll (el, node) {
return [].slice.call(node ? el.querySelectorAll(node) : $.querySelectorAll(el))
}
export function create (node, tpl) {
node = $.createElement(node)
if (tpl) node.innerHTML = tpl
return node
}
export function appendTo (target, el) {
return target.appendChild(el)
}
export function before (target, el) {
return target.insertBefore(el, target.children[0])
}
export function on (el, type, handler) {
isFn(type)
? window.addEventListener(el, type)
: el.addEventListener(type, handler)
}
export function off (el, type, handler) {
isFn(type)
? window.removeEventListener(el, type)
: el.removeEventListener(type, handler)
}
/**
* Toggle class
*
* @example
* toggleClass(el, 'active') => el.classList.toggle('active')
* toggleClass(el, 'add', 'active') => el.classList.add('active')
*/
export function toggleClass (el, type, val) {
el && el.classList[val ? type : 'toggle'](val || type)
}