forked from birdyboy18/Crumbl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrumbl.js
968 lines (796 loc) · 24.5 KB
/
crumbl.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
/*!
* @preserve Crumbl - A lightweight javascript framework
* Version 1.0.4
* http://crumbljs.com/
* copyright Glenn Naessens 2013
* MIT License
*/
(function(w, d, undefined) {
'use strict';
// @preserve Qwery - A Blazing Fast query selector engine
// https://github.com/ded/qwery
// copyright Dustin Diaz 2012
// MIT License
// Utility functions used by both qwery and crumbl
function each(a, fn) {
// not quite as fast as inline loops in older browsers so don't use liberally
var i = 0,
l = a.length;
for (; i < l; i++) fn(a[i]);
}
function flatten(ar) {
for (var r = [], i = 0, l = ar.length; i < l; ++i) arrayLike(ar[i]) ? (r = r.concat(ar[i])) : (r[r.length] = ar[i]);
return r;
}
function arrayify(ar) {
var i = 0,
l = ar.length,
r = []
for (; i < l; i++) r[i] = ar[i]
return r
}
function previous(n) {
while (n = n.previousSibling)
if (n[nodeType] == 1) break;
return n
}
function arrayLike(o) {
return (typeof o === 'object' && isFinite(o.length))
}
w.qwery = (function() {
var html = d.documentElement,
byClass = 'getElementsByClassName',
byTag = 'getElementsByTagName',
qSA = 'querySelectorAll',
useNativeQSA = 'useNativeQSA',
tagName = 'tagName',
nodeType = 'nodeType',
select, // main select() method, assign later
id = /#([\w\-]+)/,
clas = /\.[\w\-]+/g,
idOnly = /^#([\w\-]+)$/,
classOnly = /^\.([\w\-]+)$/,
tagOnly = /^([\w\-]+)$/,
tagAndOrClass = /^([\w]+)?\.([\w\-]+)$/,
splittable = /(^|,)\s*[>~+]/,
normalizr = /^\s+|\s*([,\s\+\~>]|$)\s*/g,
splitters = /[\s\>\+\~]/,
splittersMore = /(?![\s\w\-\/\?\&\=\:\.\(\)\!,@#%<>\{\}\$\*\^'"]*\]|[\s\w\+\-]*\))/,
specialChars = /([.*+?\^=!:${}()|\[\]\/\\])/g,
simple = /^(\*|[a-z0-9]+)?(?:([\.\#]+[\w\-\.#]+)?)/,
attr = /\[([\w\-]+)(?:([\|\^\$\*\~]?\=)['"]?([ \w\-\/\?\&\=\:\.\(\)\!,@#%<>\{\}\$\*\^]+)["']?)?\]/,
pseudo = /:([\w\-]+)(\(['"]?([^()]+)['"]?\))?/,
easy = new RegExp(idOnly.source + '|' + tagOnly.source + '|' + classOnly.source),
dividers = new RegExp('(' + splitters.source + ')' + splittersMore.source, 'g'),
tokenizr = new RegExp(splitters.source + splittersMore.source),
chunker = new RegExp(simple.source + '(' + attr.source + ')?' + '(' + pseudo.source + ')?')
var walker = {
' ': function(node) {
return node && node !== html && node.parentNode
},
'>': function(node, contestant) {
return node && node.parentNode == contestant.parentNode && node.parentNode
},
'~': function(node) {
return node && node.previousSibling
},
'+': function(node, contestant, p1, p2) {
if (!node) return false
return (p1 = previous(node)) && (p2 = previous(contestant)) && p1 == p2 && p1
}
}
function cache() {
this.c = {}
}
cache.prototype = {
g: function(k) {
return this.c[k] || undefined
},
s: function(k, v, r) {
v = r ? new RegExp(v) : v
return (this.c[k] = v)
}
}
var classCache = new cache(),
cleanCache = new cache(),
attrCache = new cache(),
tokenCache = new cache()
function classRegex(c) {
return classCache.g(c) || classCache.s(c, '(^|\\s+)' + c + '(\\s+|$)', 1)
}
function q(query) {
return query.match(chunker)
}
// called using `this` as element and arguments from regex group results.
// given => div.hello[title="world"]:foo('bar')
// div.hello[title="world"]:foo('bar'), div, .hello, [title="world"], title, =, world, :foo('bar'), foo, ('bar'), bar]
function interpret(whole, tag, idsAndClasses, wholeAttribute, attribute, qualifier, value, wholePseudo, pseudo, wholePseudoVal, pseudoVal) {
var i, m, k, o, classes
if (this[nodeType] !== 1) return false
if (tag && tag !== '*' && this[tagName] && this[tagName].toLowerCase() !== tag) return false
if (idsAndClasses && (m = idsAndClasses.match(id)) && m[1] !== this.id) return false
if (idsAndClasses && (classes = idsAndClasses.match(clas))) {
for (i = classes.length; i--;)
if (!classRegex(classes[i].slice(1)).test(this.className)) return false
}
if (pseudo && qwery.pseudos[pseudo] && !qwery.pseudos[pseudo](this, pseudoVal)) return false
if (wholeAttribute && !value) { // select is just for existance of attrib
o = this.attributes
for (k in o) {
if (Object.prototype.hasOwnProperty.call(o, k) && (o[k].name || k) == attribute) {
return this
}
}
}
if (wholeAttribute && !checkAttr(qualifier, getAttr(this, attribute) || '', value)) {
// select is for attrib equality
return false
}
return this
}
function isNode(el, t) {
return el && typeof el === 'object' && (t = el[nodeType]) && (t == 1 || t == 9);
}
function clean(s) {
return cleanCache.g(s) || cleanCache.s(s, s.replace(specialChars, '\\$1'))
}
function checkAttr(qualify, actual, val) {
switch (qualify) {
case '=':
return actual == val
case '^=':
return actual.match(attrCache.g('^=' + val) || attrCache.s('^=' + val, '^' + clean(val), 1))
case '$=':
return actual.match(attrCache.g('$=' + val) || attrCache.s('$=' + val, clean(val) + '$', 1))
case '*=':
return actual.match(attrCache.g(val) || attrCache.s(val, clean(val), 1))
case '~=':
return actual.match(attrCache.g('~=' + val) || attrCache.s('~=' + val, '(?:^|\\s+)' + clean(val) + '(?:\\s+|$)', 1))
case '|=':
return actual.match(attrCache.g('|=' + val) || attrCache.s('|=' + val, '^' + clean(val) + '(-|$)', 1))
}
return 0
}
// given a selector, first check for simple cases then collect all base candidate matches and filter
function _qwery(selector, _root) {
var r = [],
ret = [],
i, l, m, token, els, intr, item, root = _root,
tokens = tokenCache.g(selector) || tokenCache.s(selector, selector.split(tokenizr)),
dividedTokens = selector.match(dividers)
if (!tokens.length) return r
token = (tokens = tokens.slice(0)).pop() // copy cached tokens, take the last one
if (tokens.length && (m = tokens[tokens.length - 1].match(idOnly))) root = byId(_root, m[1])
if (!root) return r
intr = q(token)
// collect base candidates to filter
els = root !== _root && root[nodeType] !== 9 && dividedTokens && /^[+~]$/.test(dividedTokens[dividedTokens.length - 1]) ?
function(r) {
while (root = root.nextSibling) {
root[nodeType] == 1 && (intr[1] ? intr[1] == root[tagName].toLowerCase() : 1) && (r[r.length] = root)
}
return r
}([]) :
root[byTag](intr[1] || '*')
// filter elements according to the right-most part of the selector
for (i = 0, l = els.length; i < l; i++) {
if (item = interpret.apply(els[i], intr)) r[r.length] = item
}
if (!tokens.length) return r
// filter further according to the rest of the selector (the left side)
each(r, function(e) {
if (ancestorMatch(e, tokens, dividedTokens)) ret[ret.length] = e
})
return ret
}
// compare element to a selector
function is(el, selector, root) {
if (isNode(selector)) return el == selector
if (arrayLike(selector)) return !!~flatten(selector).indexOf(el) // if selector is an array, is el a member?
var selectors = selector.split(','),
tokens, dividedTokens
while (selector = selectors.pop()) {
tokens = tokenCache.g(selector) || tokenCache.s(selector, selector.split(tokenizr))
dividedTokens = selector.match(dividers)
tokens = tokens.slice(0) // copy array
if (interpret.apply(el, q(tokens.pop())) && (!tokens.length || ancestorMatch(el, tokens, dividedTokens, root))) {
return true
}
}
return false
}
// given elements matching the right-most part of a selector, filter out any that don't match the rest
function ancestorMatch(el, tokens, dividedTokens, root) {
var cand
// recursively work backwards through the tokens and up the dom, covering all options
function crawl(e, i, p) {
while (p = walker[dividedTokens[i]](p, e)) {
if (isNode(p) && (interpret.apply(p, q(tokens[i])))) {
if (i) {
if (cand = crawl(p, i - 1, p)) return cand
} else return p
}
}
}
return (cand = crawl(el, tokens.length - 1, el)) && (!root || isAncestor(cand, root))
}
function uniq(ar) {
var a = [],
i, j;
o: for (i = 0; i < ar.length; ++i) {
for (j = 0; j < a.length; ++j)
if (a[j] == ar[i]) continue o
a[a.length] = ar[i]
}
return a
}
function normalizeRoot(root) {
if (!root) return d
if (typeof root == 'string') return qwery(root)[0]
if (!root[nodeType] && arrayLike(root)) return root[0]
return root
}
function byId(root, id, el) {
// if doc, query on it, else query the parent doc or if a detached fragment rewrite the query and run on the fragment
return root[nodeType] === 9 ? root.getElementById(id) :
root.ownerDocument &&
(((el = root.ownerDocument.getElementById(id)) && isAncestor(el, root) && el) ||
(!isAncestor(root, root.ownerDocument) && select('[id="' + id + '"]', root)[0]))
}
function qwery(selector, _root) {
var m, el, root = normalizeRoot(_root)
// easy, fast cases that we can dispatch with simple DOM calls
if (!root || !selector) return []
if (selector === w || isNode(selector)) {
return !_root || (selector !== w && isNode(root) && isAncestor(selector, root)) ? [selector] : []
}
if (selector && arrayLike(selector)) return flatten(selector)
if (m = selector.match(easy)) {
if (m[1]) return (el = byId(root, m[1])) ? [el] : []
if (m[2]) return arrayify(root[byTag](m[2]))
if (hasByClass && m[3]) return arrayify(root[byClass](m[3]))
}
return select(selector, root)
}
// where the root is not document and a relationship selector is first we have to
// do some awkward adjustments to get it to work, even with qSA
function collectSelector(root, collector) {
return function(s) {
var oid, nid
if (splittable.test(s)) {
if (root[nodeType] !== 9) {
// make sure the el has an id, rewrite the query, set root to doc and run it
if (!(nid = oid = root.getAttribute('id'))) root.setAttribute('id', nid = '__qwerymeupscotty')
s = '[id="' + nid + '"]' + s // avoid byId and allow us to match context element
collector(root.parentNode || root, s, true)
oid || root.removeAttribute('id')
}
return;
}
s.length && collector(root, s, false)
}
}
var isAncestor = 'compareDocumentPosition' in html ?
function(element, container) {
return (container.compareDocumentPosition(element) & 16) == 16
} : 'contains' in html ?
function(element, container) {
container = container[nodeType] === 9 || container == w ? html : container
return container !== element && container.contains(element)
} :
function(element, container) {
while (element = element.parentNode)
if (element === container) return 1
return 0
}, getAttr = function() {
// detect buggy IE src/href getAttribute() call
var e = d.createElement('p')
return ((e.innerHTML = '<a href="#x">x</a>') && e.firstChild.getAttribute('href') != '#x') ?
function(e, a) {
return a === 'class' ? e.className : (a === 'href' || a === 'src') ?
e.getAttribute(a, 2) : e.getAttribute(a)
} :
function(e, a) {
return e.getAttribute(a)
}
}(),
hasByClass = !! d[byClass]
// has native qSA support
,
hasQSA = d.querySelector && d[qSA]
// use native qSA
,
selectQSA = function(selector, root) {
var result = [],
ss, e
try {
if (root[nodeType] === 9 || !splittable.test(selector)) {
// most work is done right here, defer to qSA
return arrayify(root[qSA](selector))
}
// special case where we need the services of `collectSelector()`
each(ss = selector.split(','), collectSelector(root, function(ctx, s) {
e = ctx[qSA](s)
if (e.length == 1) result[result.length] = e.item(0)
else if (e.length) result = result.concat(arrayify(e))
}))
return ss.length > 1 && result.length > 1 ? uniq(result) : result
} catch (ex) {}
return selectNonNative(selector, root)
}
// no native selector support
, selectNonNative = function(selector, root) {
var result = [],
items, m, i, l, r, ss
selector = selector.replace(normalizr, '$1')
if (m = selector.match(tagAndOrClass)) {
r = classRegex(m[2])
items = root[byTag](m[1] || '*')
for (i = 0, l = items.length; i < l; i++) {
if (r.test(items[i].className)) result[result.length] = items[i]
}
return result
}
// more complex selector, get `_qwery()` to do the work for us
each(ss = selector.split(','), collectSelector(root, function(ctx, s, rewrite) {
r = _qwery(s, ctx)
for (i = 0, l = r.length; i < l; i++) {
if (ctx[nodeType] === 9 || rewrite || isAncestor(r[i], root)) result[result.length] = r[i]
}
}))
return ss.length > 1 && result.length > 1 ? uniq(result) : result
}, configure = function(options) {
// configNativeQSA: use fully-internal selector or native qSA where present
if (options[useNativeQSA] !== undefined)
select = !options[useNativeQSA] ? selectNonNative : hasQSA ? selectQSA : selectNonNative
}
configure({
useNativeQSA: true
})
qwery.configure = configure
qwery.uniq = uniq
qwery.is = is
qwery.pseudos = {}
return qwery
})();
var readyfn = [],
loadedfn = [],
domready = false,
pageloaded = false;
// Fire any function calls on ready event
function fireReady() {
var i;
domready = true;
for (i = 0; i < readyfn.length; i += 1) {
readyfn[i]();
}
readyfn = [];
}
// Fire any function calls on loaded event
function fireLoaded() {
var i;
pageloaded = true;
// For browsers with no DOM loaded support
if (!domready) {
fireReady();
}
for (i = 0; i < loadedfn.length; i += 1) {
loadedfn[i]();
}
loadedfn = [];
}
// Check DOM ready, page loaded
if (d.addEventListener) {
// Standards
d.addEventListener('DOMContentLoaded', fireReady, false);
w.addEventListener('load', fireLoaded, false);
} else if (d.attachEvent) {
// IE
d.attachEvent('onreadystatechange', fireReady);
// IE < 9
w.attachEvent('onload', fireLoaded);
} else {
// Anything else
w.onload = fireLoaded;
}
// Handle standard method value returns
function returnValues(values) {
if (values.length === 1) {
values = values[0];
}
return values;
}
// Event handler
function manageEvent(event, handler, remove, nodes) {
each(nodes, function(elm) {
if (d.addEventListener) {
remove ? elm.removeEventListener(event, elm[event], false) : elm.addEventListener(event, handler, false);
} else if (d.attachEvent) {
remove ? elm.detachEvent('on' + event, elm[event]) : elm.attachEvent('on' + event, handler);
}
elm[event] = (remove ? null : handler);
});
}
function manageClass(classes, action, nodes) {
var values = [],
classarray,
l,
classname,
search,
has,
i,
item,
classListSupport = d.documentElement.classList;
if (classes) {
// Trim any whitespace
classarray = classes.split(/\s+/);
l = classarray.length;
each(nodes, function(elm) {
for (i = 0; i < l; i += 1) {
item = classarray[i];
if (classListSupport) {
if (action === 'has') {
values.push(elm.classList.contains(item));
} else if (action === 'toggle') {
elm.classList.toggle(item);
} else if (action === 'add') {
elm.classList.add(item);
} else { // remove
elm.classList.remove(item);
}
} else {
classname = elm.className || '';
search = new RegExp('\\b' + item + '\\b', 'g');
has = !!classname.match(search);
if (action === 'has') {
values.push(has);
} else if (action === 'toggle') {
elm.className = has ? classname.replace(search, '') : classname + " " + item;
} else if (action === 'add') {
if (!has) {
elm.className = classname + " " + classes;
}
} else { // remove
elm.className = classname.replace(search, '');
}
}
}
// remove spaces - seems a bit unnecessary now that I think about it.
//elm.className = elm.className.replace(/^\s+|\s+$/g, '');
});
if (values.length > 0) {
return returnValues(values);
}
}
}
function manageAttributes(name, value, remove, nodes) {
var values = [];
each(nodes, function(elm) {
if (name) {
name = name.toLowerCase();
if (remove) {
elm.removeAttribute(name);
} else if (value) {
elm.setAttribute(name, value);
} else if (elm.getAttribute(name)) {
values.push(elm.getAttribute(name));
} else {
values.push(null);
}
}
});
if (values.length > 0) {
return returnValues(values);
}
}
function insertIntoDOM(method, subject, nodes) {
var children = [],
l;
if (subject.nodes && subject.nodes !== 0) {
children = subject.nodes;
} else if (subject.nodeType && subject.nodeType === 1) {
children.push(subject);
}
l = children.length;
if (method === 'append') {
each(nodes, function(elm) {
for (var i = 0; i < l; i++) {
elm.appendChild(children[i]);
}
});
} else {
each(nodes, function(elm) {
for (var i = 0; i < l; i++) {
elm.insertBefore(children[i], elm.firstChild);
}
});
}
}
function traverse(to, nodes) {
if (to) {
var temp = [],
i, c = nodes.length;
switch (to) {
case 'children':
case 'siblings':
for (i = 0; i < c; i++) {
var node = (to === 'siblings' ? nodes[i].parentNode.firstChild : nodes[i].firstChild),
skipSelf = nodes[i];
do {
if (node && node.nodeType === 1 && node !== skipSelf) {
temp.push(node);
}
node = node.nextSibling;
} while (node);
}
break;
case 'parent':
for (i = 0; i < c; i++) {
temp.push(nodes[i].parentNode);
}
break;
case 'next':
for (i = 0; i < c; i++) {
var next = nodes[i];
do {
next = next.nextSibling;
} while (next && next.nodeType !== 1);
temp.push(next);
}
break;
case 'previous':
for (i = 0; i < c; i++) {
var prev = nodes[i];
do {
prev = prev.previousSibling;
} while (prev && prev.nodeType !== 1);
temp.push(prev);
}
break;
}
nodes = temp;
}
return nodes;
}
// The actual crumbl. Use qwery to gather the requested elements and return crumbl
function crumbl(selector, context) {
return new crumbl.methods.init(selector, context);
}
// The crumble object prototype
crumbl.methods = crumbl.prototype = {
init: function(selector, context){
var nodes = [],
context = context || d,
q = null,
c = 0,
i,
oneResultSet = false;
if (selector) {
if (selector.nodeType && selector.nodeType === 1) {
// return node as crumbl object
nodes = [selector];
c = 1;
} else if (selector.constructor && selector.call && selector.apply) {
//the selector is a function -> execute on dom ready
readyfn.push(selector);
c = false;
return null;
} else if (selector === w) {
nodes = [w];
c = 1;
} else if (selector instanceof Array) {
//the nodes have been passed to instantiate a new crumbl object from a
//nodes-altering function
nodes = selector;
c = nodes.length;
} else if (typeof selector === 'string') {
if (selector.match(/<\/*[a-z][^>]+?>/gi)) {
// selector is an html tag: create the element, add to nodes
var container = d.createElement('div');
container.innerHTML = selector;
nodes.push(container.firstChild);
c = 1;
} else {
//normal behavior: use qwery to find the selector and return nodes
// context can be
// nothing, -> document
// a string (a selector)
// a node
// Array of nodes (when passed through .find())
if (context === d) {
q = qwery(selector);
c = q.length;
oneResultSet = true;
} else if (typeof context === 'string') {
q = qwery(selector);
c = q.length;
oneResultSet = true;
} else if ((context.nodeType && context.nodeType === 1) || (context instanceof Array && context.length === 1)) {
q = qwery(selector, (context[0] || context));
c = q.length;
oneResultSet = true;
} else if (context instanceof Array) {
var contextcount = context.length,
contexti,
totalc = 0;
for (contexti = 0; contexti < contextcount; contexti++) {
q = qwery(selector, context[contexti]);
c = q.length;
totalc += c;
for (i = 0; i < c; i++) {
nodes.push(q[i]);
}
c = totalc;
}
}
if (oneResultSet) {
for (i = 0; i < c; i++) {
nodes.push(q[i]);
}
}
}
}
}
this.nodes = nodes;
this.count = c;
return this;
},
// Fire on DOM ready
ready: function(fn) {
if (fn) {
if (domready) {
fn();
} else {
readyfn.push(fn);
}
}
},
// Fire on page loaded
loaded: function(fn) {
if (fn) {
if (pageloaded) {
fn();
} else {
loadedfn.push(fn);
}
}
},
// Perform an action on every node
each: function(fn) {
if (typeof fn === "function") {
each(this.nodes, function(elm) {
return fn.apply(elm, arguments);
});
}
return this;
},
// Find selector in element chilren
find: function(s) {
// return a new crumbl object with qwery return results
return new crumbl.methods.init(s, this.nodes);
},
// Traversing
children: function() {
return new crumbl.methods.init(traverse('children', this.nodes));
},
siblings: function() {
return new crumbl.methods.init(traverse('siblings', this.nodes));
},
parent: function() {
return new crumbl.methods.init(traverse('parent', this.nodes));
},
next: function() {
return new crumbl.methods.init(traverse('next', this.nodes));
},
prev: function() {
return new crumbl.methods.init(traverse('previous', this.nodes));
},
only: function() {
//returns the first node in the nodelist
var el = this.nodes[0];
if (el) {
return el;
}
},
// Appending elements to the DOM
append: function(elm) {
insertIntoDOM('append', elm, this.nodes);
return this;
},
prepend: function(elm) {
insertIntoDOM('prepend', elm, this.nodes);
return this;
},
// Remove all children
empty: function() {
each(this.nodes, function(elm) {
while (elm.hasChildNodes()) {
elm.removeChild(elm.lastChild);
}
});
return this;
},
// Remove node
remove: function() {
each(this.nodes, function(elm) {
// Catch error in unlikely case elm has been removed
try {
elm.parentNode.removeChild(elm);
} catch (e) {}
});
// Clear nodes after remove
this.nodes = [];
return this;
},
// Cloning elements
clone: function(deep) {
//default to true
deep = ((deep === true || deep === undefined) ? true : false);
var temp = [];
each(this.nodes, function(elm) {
if(elm.nodeType || elm.nodeType === 1){
temp.push(elm.cloneNode(deep));
}
});
return new crumbl.methods.init(temp);
},
// CSS Class Management
hasClass: function(c) {
return manageClass(c, 'has', this.nodes);
},
addClass: function(c) {
manageClass(c, 'add', this.nodes);
return this;
},
removeClass: function(c) {
manageClass(c, 'remove', this.nodes);
return this;
},
toggleClass: function(c) {
manageClass(c, 'toggle', this.nodes);
return this;
},
// Get/Set innerHTML optionally before/after
html: function(value) {
var values = [];
each(this.nodes, function(elm) {
if (value) {
elm.innerHTML = value;
} else {
values.push(elm.innerHTML);
}
});
if (values.length > 0) {
return returnValues(values);
}
return this;
},
// Get/Set/remove HTML attributes
attr: function(name, value) {
if (name) {
if (value) {
manageAttributes(name, value, false, this.nodes);
return this;
} else {
return manageAttributes(name, false, false, this.nodes);
}
}
},
removeAttr: function(name) {
manageAttributes(name, false, true, this.nodes);
return this;
},
// Event handlers
on: function(event, handler) {
manageEvent(event, handler, false, this.nodes);
return this;
},
off: function(event) {
manageEvent(event, null, true, this.nodes);
return this;
}
};
crumbl.methods.init.prototype = crumbl.methods;
// Make crumbl globally available with $ for easy use.
w.$ = crumbl;
})(window, document);