/
dom.js
2025 lines (1802 loc) · 63.3 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
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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** section: DOM, related to: Element
* $(id) -> Element
* $(id...) -> [Element]...
* - id (String | Element): A DOM node or a string that references a node's
* ID.
*
* If provided with a string, returns the element in the document with
* matching ID; otherwise returns the passed element.
*
* Takes in an arbitrary number of arguments. Returns one `Element` if given
* one argument; otherwise returns an array of `Element`s.
*
* All elements returned by the function are "extended" with `Element`
* instance methods.
**/
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
elements.push($(arguments[i]));
return elements;
}
if (Object.isString(element))
element = document.getElementById(element);
return Element.extend(element);
}
if (Prototype.BrowserFeatures.XPath) {
document._getElementsByXPath = function(expression, parentElement) {
var results = [];
var query = document.evaluate(expression, $(parentElement) || document,
null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0, length = query.snapshotLength; i < length; i++)
results.push(Element.extend(query.snapshotItem(i)));
return results;
};
}
/*--------------------------------------------------------------------------*/
if (!window.Node) var Node = { };
if (!Node.ELEMENT_NODE) {
// DOM level 2 ECMAScript Language Binding
Object.extend(Node, {
ELEMENT_NODE: 1,
ATTRIBUTE_NODE: 2,
TEXT_NODE: 3,
CDATA_SECTION_NODE: 4,
ENTITY_REFERENCE_NODE: 5,
ENTITY_NODE: 6,
PROCESSING_INSTRUCTION_NODE: 7,
COMMENT_NODE: 8,
DOCUMENT_NODE: 9,
DOCUMENT_TYPE_NODE: 10,
DOCUMENT_FRAGMENT_NODE: 11,
NOTATION_NODE: 12
});
}
/** section: DOM
* class Element
**/
/**
* new Element(tagName[, attributes])
* - tagName (String): The name of the HTML element to create.
* - attributes (Object): A list of attribute/value pairs to set on the
* element.
*
* Creates an HTML element with `tagName` as the tag name.
**/
(function(global) {
// setAttribute is broken in IE (particularly when setting name attribute)
// see: http://msdn.microsoft.com/en-us/library/ms536389.aspx
var SETATTRIBUTE_IGNORES_NAME = (function(){
var elForm = document.createElement("form");
var elInput = document.createElement("input");
var root = document.documentElement;
elInput.setAttribute("name", "test");
elForm.appendChild(elInput);
root.appendChild(elForm);
var isBuggy = elForm.elements
? (typeof elForm.elements.test == "undefined")
: null;
root.removeChild(elForm);
elForm = elInput = null;
return isBuggy;
})();
var element = global.Element;
global.Element = function(tagName, attributes) {
attributes = attributes || { };
tagName = tagName.toLowerCase();
var cache = Element.cache;
if (SETATTRIBUTE_IGNORES_NAME && attributes.name) {
tagName = '<' + tagName + ' name="' + attributes.name + '">';
delete attributes.name;
return Element.writeAttribute(document.createElement(tagName), attributes);
}
if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
};
Object.extend(global.Element, element || { });
if (element) global.Element.prototype = element.prototype;
})(this);
Element.cache = { };
Element.idCounter = 1;
Element.Methods = {
/**
* Element.visible(@element) -> boolean
*
* Tells whether `element` is visible (i.e., whether its inline `display`
* CSS property is set to `none`.
**/
visible: function(element) {
return $(element).style.display != 'none';
},
/**
* Element.toggle(@element) -> Element
*
* Toggles the visibility of `element`. Returns `element`.
**/
toggle: function(element) {
element = $(element);
Element[Element.visible(element) ? 'hide' : 'show'](element);
return element;
},
/**
* Element.hide(@element) -> Element
*
* Sets `display: none` on `element`. Returns `element`.
**/
hide: function(element) {
element = $(element);
element.style.display = 'none';
return element;
},
/**
* Element.show(@element) -> Element
*
* Removes `display: none` on `element`. Returns `element`.
**/
show: function(element) {
element = $(element);
element.style.display = '';
return element;
},
/**
* Element.remove(@element) -> Element
*
* Completely removes `element` from the document and returns it.
**/
remove: function(element) {
element = $(element);
element.parentNode.removeChild(element);
return element;
},
/**
* Element.update(@element[, newContent]) -> Element
*
* Replaces _the content_ of `element` with the `newContent` argument and
* returns `element`.
*
* `newContent` may be in any of these forms:
* - [[String]]: A string of HTML to be parsed and rendered
* - [[Element]]: An Element instance to insert
* - ...any object with a `toElement` method: The method is called and the resulting element used
* - ...any object with a `toHTML` method: The method is called and the resulting HTML string
* is parsed and rendered
*
* If `newContent` is omitted, the element's content is blanked out (i.e.,
* replaced with an empty string).
*
* If `newContent` is a string and contains one or more inline `<script>` tags, the scripts
* are scheduled to be evaluated after a very brief pause (using [[Function#defer]]) to allow
* the browser to finish updating the DOM. Note that the scripts are evaluated
* in the scope of [[String#evalScripts]], not in the global scope, which has important
* ramifications for your `var`s and `function`s. See [[String#evalScripts]] for details.
**/
update: (function(){
// see: http://support.microsoft.com/kb/276228
var SELECT_ELEMENT_INNERHTML_BUGGY = (function(){
var el = document.createElement("select"),
isBuggy = true;
el.innerHTML = "<option value=\"test\">test</option>";
if (el.options && el.options[0]) {
isBuggy = el.options[0].nodeName.toUpperCase() !== "OPTION";
}
el = null;
return isBuggy;
})();
// see: http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
var TABLE_ELEMENT_INNERHTML_BUGGY = (function(){
try {
var el = document.createElement("table");
if (el && el.tBodies) {
el.innerHTML = "<tbody><tr><td>test</td></tr></tbody>";
var isBuggy = typeof el.tBodies[0] == "undefined";
el = null;
return isBuggy;
}
} catch (e) {
return true;
}
})();
var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () {
var s = document.createElement("script"),
isBuggy = false;
try {
s.appendChild(document.createTextNode(""));
isBuggy = !s.firstChild ||
s.firstChild && s.firstChild.nodeType !== 3;
} catch (e) {
isBuggy = true;
}
s = null;
return isBuggy;
})();
function update(element, content) {
element = $(element);
if (content && content.toElement)
content = content.toElement();
if (Object.isElement(content))
return element.update().insert(content);
content = Object.toHTML(content);
var tagName = element.tagName.toUpperCase();
if (tagName === 'SCRIPT' && SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING) {
// scripts are not evaluated when updating SCRIPT element
element.text = content;
return element;
}
if (SELECT_ELEMENT_INNERHTML_BUGGY || TABLE_ELEMENT_INNERHTML_BUGGY) {
if (tagName in Element._insertionTranslations.tags) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
Element._getContentFromAnonymousElement(tagName, content.stripScripts())
.each(function(node) {
element.appendChild(node)
});
}
else {
element.innerHTML = content.stripScripts();
}
}
else {
element.innerHTML = content.stripScripts();
}
content.evalScripts.bind(content).defer();
return element;
}
return update;
})(),
/**
* Element.replace(@element[, newContent]) -> Element
*
* Replaces `element` _itself_ with `newContent` and returns `element`.
*
* Keep in mind that this method returns the element that has just been
* removed — not the element that took its place.
**/
replace: function(element, content) {
element = $(element);
if (content && content.toElement) content = content.toElement();
else if (!Object.isElement(content)) {
content = Object.toHTML(content);
var range = element.ownerDocument.createRange();
range.selectNode(element);
content.evalScripts.bind(content).defer();
content = range.createContextualFragment(content.stripScripts());
}
element.parentNode.replaceChild(content, element);
return element;
},
/**
* Element.insert(@element, content) -> Element
* - content (String | Element | Object): The content to insert.
*
* Inserts content `above`, `below`, at the `top`, and/or at the `bottom` of the
* given element, depending on the option(s) given.
*
* `insert` accepts content in any of these forms:
* - [[String]]: A string of HTML to be parsed and rendered
* - [[Element]]: An Element instance to insert
* - ...any object with a `toElement` method: The method is called and the resulting element used
* - ...any object with a `toHTML` method: The method is called and the resulting HTML string
* is parsed and rendered
*
* The `content` argument can be the content to insert, in which case the implied
* insertion point is `bottom`, or an object that specifies one or more insertion
* points (e.g., `{ bottom: "foo", top: "bar" }`).
*
* Accepted insertion points are:
* - `before` (as `element`'s previous sibling)
* - `after` (as `element's` next sibling)
* - `top` (as `element`'s first child)
* - `bottom` (as `element`'s last child)
*
* <h4>Examples</h4>
*
* Insert the given HTML at the bottom of the element (using the default):
*
* $('myelement').insert("<p>HTML to append</p>");
*
* $('myelement').insert({
* top: new Element('img', {src: 'logo.png'})
* });
*
* Put `hr`s `before` and `after` the element:
*
* $('myelement').insert({
* before: "<hr>",
* after: "<hr>"
* });
**/
insert: function(element, insertions) {
element = $(element);
if (Object.isString(insertions) || Object.isNumber(insertions) ||
Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
insertions = {bottom:insertions};
var content, insert, tagName, childNodes;
for (var position in insertions) {
content = insertions[position];
position = position.toLowerCase();
insert = Element._insertionTranslations[position];
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) {
insert(element, content);
continue;
}
content = Object.toHTML(content);
tagName = ((position == 'before' || position == 'after')
? element.parentNode : element).tagName.toUpperCase();
childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
if (position == 'top' || position == 'after') childNodes.reverse();
childNodes.each(insert.curry(element));
content.evalScripts.bind(content).defer();
}
return element;
},
/**
* Element.wrap(@element, wrapper[, attributes]) -> Element
* - wrapper (Element | String): An element to wrap `element` inside, or
* else a string representing the tag name of an element to be created.
* - attributes (Object): A set of attributes to apply to the wrapper
* element. Refer to the [[Element]] constructor for usage.
*
* Wraps an element inside another, then returns the wrapper.
**/
wrap: function(element, wrapper, attributes) {
element = $(element);
if (Object.isElement(wrapper))
$(wrapper).writeAttribute(attributes || { });
else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
else wrapper = new Element('div', wrapper);
if (element.parentNode)
element.parentNode.replaceChild(wrapper, element);
wrapper.appendChild(element);
return wrapper;
},
/**
* Element.inspect(@element) -> String
*
* Returns the debug-oriented string representation of `element`.
**/
inspect: function(element) {
element = $(element);
var result = '<' + element.tagName.toLowerCase();
$H({'id': 'id', 'className': 'class'}).each(function(pair) {
var property = pair.first(), attribute = pair.last();
var value = (element[property] || '').toString();
if (value) result += ' ' + attribute + '=' + value.inspect(true);
});
return result + '>';
},
/**
* Element.recursivelyCollect(@element, property) -> [Element...]
*
* Recursively collects elements whose relationship to `element` is
* specified by `property`. `property` has to be a _property_ (a method
* won't do!) of `element` that points to a single DOM node (e.g.,
* `nextSibling` or `parentNode`).
**/
recursivelyCollect: function(element, property) {
element = $(element);
var elements = [];
while (element = element[property])
if (element.nodeType == 1)
elements.push(Element.extend(element));
return elements;
},
/**
* Element.ancestors(@element) -> [Element...]
*
* Collects all of `element`'s ancestors and returns them as an array of
* elements.
**/
ancestors: function(element) {
return Element.recursivelyCollect(element, 'parentNode');
},
/**
* Element.descendants(@element) -> [Element...]
*
* Collects all of element's descendants and returns them as an array of
* elements.
**/
descendants: function(element) {
return Element.select(element, "*");
},
/**
* Element.firstDescendant(@element) -> Element
*
* Returns the first child that is an element.
*
* This is opposed to the `firstChild` DOM property, which will return
* any node, including text nodes.
**/
firstDescendant: function(element) {
element = $(element).firstChild;
while (element && element.nodeType != 1) element = element.nextSibling;
return $(element);
},
/**
* Element.immediateDescendants(@element) -> [Element...]
*
* Collects all of `element`'s immediate descendants (i.e., children) and
* returns them as an array of elements.
**/
immediateDescendants: function(element) {
if (!(element = $(element).firstChild)) return [];
while (element && element.nodeType != 1) element = element.nextSibling;
if (element) return [element].concat($(element).nextSiblings());
return [];
},
/**
* Element.previousSiblings(@element) -> [Element...]
*
* Collects all of `element`'s previous siblings and returns them as an
* array of elements.
**/
previousSiblings: function(element) {
return Element.recursivelyCollect(element, 'previousSibling');
},
/**
* Element.nextSiblings(@element) -> [Element...]
*
* Collects all of `element`'s next siblings and returns them as an array
* of elements.
**/
nextSiblings: function(element) {
return Element.recursivelyCollect(element, 'nextSibling');
},
/**
* Element.siblings(@element) -> [Element...]
* Collects all of element's siblings and returns them as an array of
* elements.
**/
siblings: function(element) {
element = $(element);
return Element.previousSiblings(element).reverse()
.concat(Element.nextSiblings(element));
},
/**
* Element.match(@element, selector) -> boolean
* - selector (String): A CSS selector.
*
* Checks if `element` matches the given CSS selector.
**/
match: function(element, selector) {
if (Object.isString(selector))
selector = new Selector(selector);
return selector.match($(element));
},
/**
* Element.up(@element[, expression[, index = 0]]) -> Element
* Element.up(@element[, index = 0]) -> Element
* - expression (String): A CSS selector.
*
* Returns `element`'s first ancestor (or the Nth ancestor, if `index`
* is specified) that matches `expression`. If no `expression` is
* provided, all ancestors are considered. If no ancestor matches these
* criteria, `undefined` is returned.
**/
up: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(element.parentNode);
var ancestors = Element.ancestors(element);
return Object.isNumber(expression) ? ancestors[expression] :
Selector.findElement(ancestors, expression, index);
},
/**
* Element.down(@element[, expression[, index = 0]]) -> Element
* Element.down(@element[, index = 0]) -> Element
* - expression (String): A CSS selector.
*
* Returns `element`'s first descendant (or the Nth descendant, if `index`
* is specified) that matches `expression`. If no `expression` is
* provided, all descendants are considered. If no descendant matches these
* criteria, `undefined` is returned.
**/
down: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return Element.firstDescendant(element);
return Object.isNumber(expression) ? Element.descendants(element)[expression] :
Element.select(element, expression)[index || 0];
},
/**
* Element.previous(@element[, expression[, index = 0]]) -> Element
* Element.previous(@element[, index = 0]) -> Element
* - expression (String): A CSS selector.
*
* Returns `element`'s first previous sibling (or the Nth, if `index`
* is specified) that matches `expression`. If no `expression` is
* provided, all previous siblings are considered. If none matches these
* criteria, `undefined` is returned.
**/
previous: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
var previousSiblings = Element.previousSiblings(element);
return Object.isNumber(expression) ? previousSiblings[expression] :
Selector.findElement(previousSiblings, expression, index);
},
/**
* Element.next(@element[, expression[, index = 0]]) -> Element
* Element.next(@element[, index = 0]) -> Element
* - expression (String): A CSS selector.
*
* Returns `element`'s first following sibling (or the Nth, if `index`
* is specified) that matches `expression`. If no `expression` is
* provided, all following siblings are considered. If none matches these
* criteria, `undefined` is returned.
**/
next: function(element, expression, index) {
element = $(element);
if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
var nextSiblings = Element.nextSiblings(element);
return Object.isNumber(expression) ? nextSiblings[expression] :
Selector.findElement(nextSiblings, expression, index);
},
/**
* Element.select(@element, selector...) -> [Element...]
* - selector (String): A CSS selector.
*
* Takes an arbitrary number of CSS selectors and returns an array of
* descendants of `element` that match any of them.
**/
select: function(element) {
var args = Array.prototype.slice.call(arguments, 1);
return Selector.findChildElements(element, args);
},
/**
* Element.adjacent(@element, selector...) -> [Element...]
* - selector (String): A CSS selector.
*
* Finds all siblings of the current element that match the given
* selector(s).
**/
adjacent: function(element) {
var args = Array.prototype.slice.call(arguments, 1);
return Selector.findChildElements(element.parentNode, args).without(element);
},
/**
* Element.identify(@element) -> String
*
* Returns `element`'s ID. If `element` does not have an ID, one is
* generated, assigned to `element`, and returned.
**/
identify: function(element) {
element = $(element);
var id = Element.readAttribute(element, 'id');
if (id) return id;
do { id = 'anonymous_element_' + Element.idCounter++ } while ($(id));
Element.writeAttribute(element, 'id', id);
return id;
},
/**
* Element.readAttribute(@element, attributeName) -> String | null
*
* Returns the value of `element`'s attribute with the given name.
**/
readAttribute: function(element, name) {
element = $(element);
if (Prototype.Browser.IE) {
var t = Element._attributeTranslations.read;
if (t.values[name]) return t.values[name](element, name);
if (t.names[name]) name = t.names[name];
if (name.include(':')) {
return (!element.attributes || !element.attributes[name]) ? null :
element.attributes[name].value;
}
}
return element.getAttribute(name);
},
/**
* Element.writeAttribute(@element, attribute[, value = true]) -> Element
* Element.writeAttribute(@element, attributes) -> Element
*
* Adds, changes, or removes attributes passed as either a hash or a
* name/value pair.
**/
writeAttribute: function(element, name, value) {
element = $(element);
var attributes = { }, t = Element._attributeTranslations.write;
if (typeof name == 'object') attributes = name;
else attributes[name] = Object.isUndefined(value) ? true : value;
for (var attr in attributes) {
name = t.names[attr] || attr;
value = attributes[attr];
if (t.values[attr]) name = t.values[attr](element, value);
if (value === false || value === null)
element.removeAttribute(name);
else if (value === true)
element.setAttribute(name, name);
else element.setAttribute(name, value);
}
return element;
},
/**
* Element.getHeight(@element) -> Number
*
* Returns the height of `element`.
**/
getHeight: function(element) {
return Element.getDimensions(element).height;
},
/**
* Element.getWidth(@element) -> Number
*
* Returns the width of `element`.
**/
getWidth: function(element) {
return Element.getDimensions(element).width;
},
/**
* Element.classNames(@element) -> [String...]
*
* Returns a new instance of [[Element.ClassNames]], an [[Enumerable]]
* object used to read and write CSS class names of `element`.
**/
classNames: function(element) {
return new Element.ClassNames(element);
},
/**
* Element.hasClassName(@element, className) -> Boolean
*
* Checks whether `element` has the given CSS class name.
**/
hasClassName: function(element, className) {
if (!(element = $(element))) return;
var elementClassName = element.className;
return (elementClassName.length > 0 && (elementClassName == className ||
new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
},
/**
* Element.addClassName(@element, className) -> Element
*
* Adds a CSS class to `element`.
**/
addClassName: function(element, className) {
if (!(element = $(element))) return;
if (!Element.hasClassName(element, className))
element.className += (element.className ? ' ' : '') + className;
return element;
},
/**
* Element.removeClassName(@element, className) -> Element
*
* Removes a CSS class from `element`.
**/
removeClassName: function(element, className) {
if (!(element = $(element))) return;
element.className = element.className.replace(
new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
return element;
},
/**
* Element.toggleClassName(@element, className) -> Element
*
* Toggles the presence of a CSS class on `element`.
**/
toggleClassName: function(element, className) {
if (!(element = $(element))) return;
return Element[Element.hasClassName(element, className) ?
'removeClassName' : 'addClassName'](element, className);
},
/**
* Element.cleanWhitespace(@element) -> Element
*
* Removes whitespace-only text node children from `element`.
**/
cleanWhitespace: function(element) {
element = $(element);
var node = element.firstChild;
while (node) {
var nextNode = node.nextSibling;
if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
element.removeChild(node);
node = nextNode;
}
return element;
},
/**
* Element.empty(@element) -> Element
*
* Tests whether `element` is empty (i.e., contains only whitespace).
**/
empty: function(element) {
return $(element).innerHTML.blank();
},
/**
* Element.descendantOf(@element, ancestor) -> Boolean
*
* Checks if `element` is a descendant of `ancestor`.
**/
descendantOf: function(element, ancestor) {
element = $(element), ancestor = $(ancestor);
if (element.compareDocumentPosition)
return (element.compareDocumentPosition(ancestor) & 8) === 8;
if (ancestor.contains)
return ancestor.contains(element) && ancestor !== element;
while (element = element.parentNode)
if (element == ancestor) return true;
return false;
},
/**
* Element.scrollTo(@element) -> Element
*
* Scrolls the window so that `element` appears at the top of the viewport.
**/
scrollTo: function(element) {
element = $(element);
var pos = Element.cumulativeOffset(element);
window.scrollTo(pos[0], pos[1]);
return element;
},
/**
* Element.getStyle(@element, style) -> String | null
* - style (String): The property name to be retrieved.
*
* Returns the given CSS property value of `element`. The property can be
* specified in either its CSS form (`font-size`) or its camelized form
* (`fontSize`).
**/
getStyle: function(element, style) {
element = $(element);
style = style == 'float' ? 'cssFloat' : style.camelize();
var value = element.style[style];
if (!value || value == 'auto') {
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css[style] : null;
}
if (style == 'opacity') return value ? parseFloat(value) : 1.0;
return value == 'auto' ? null : value;
},
/**
* Element.getOpacity(@element) -> String | null
*
* Returns the opacity of the element.
**/
getOpacity: function(element) {
return $(element).getStyle('opacity');
},
/**
* Element.setStyle(@element, styles) -> Element
*
* Modifies `element`'s CSS style properties.
*
* Styles are passed as an object of property-value pairs in which the
* properties are specified in their camelized form (e.g., `fontSize`).
**/
setStyle: function(element, styles) {
element = $(element);
var elementStyle = element.style, match;
if (Object.isString(styles)) {
element.style.cssText += ';' + styles;
return styles.include('opacity') ?
element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
}
for (var property in styles)
if (property == 'opacity') element.setOpacity(styles[property]);
else
elementStyle[(property == 'float' || property == 'cssFloat') ?
(Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
property] = styles[property];
return element;
},
/**
* Element.setOpacity(@element, value) -> Element
*
* Sets the opacity of `element`.
**/
setOpacity: function(element, value) {
element = $(element);
element.style.opacity = (value == 1 || value === '') ? '' :
(value < 0.00001) ? 0 : value;
return element;
},
/**
* Element.getDimensions(@element) -> Object
*
* Finds the computed width and height of `element` and returns them as
* key/value pairs of an object.
**/
getDimensions: function(element) {
element = $(element);
var display = Element.getStyle(element, 'display');
if (display != 'none' && display != null) // Safari bug
return {width: element.offsetWidth, height: element.offsetHeight};
// All *Width and *Height properties give 0 on elements with display none,
// so enable the element temporarily
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
var originalDisplay = els.display;
els.visibility = 'hidden';
if (originalPosition != 'fixed') // Switching fixed to absolute causes issues in Safari
els.position = 'absolute';
els.display = 'block';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = originalDisplay;
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
},
/**
* Element.makePositioned(@element) -> Element
*
* Allows for the easy creation of a CSS containing block by setting
* `element`'s CSS `position` to `relative` if its initial position is
* either `static` or `undefined`.
**/
makePositioned: function(element) {
element = $(element);
var pos = Element.getStyle(element, 'position');
if (pos == 'static' || !pos) {
element._madePositioned = true;
element.style.position = 'relative';
// Opera returns the offset relative to the positioning context, when an
// element is position relative but top and left have not been defined
if (Prototype.Browser.Opera) {
element.style.top = 0;
element.style.left = 0;
}
}
return element;
},
/**
* Element.undoPositioned(@element) -> Element
*
* Sets `element` back to the state it was in _before_
* [[Element.makePositioned]] was applied to it.
**/
undoPositioned: function(element) {
element = $(element);
if (element._madePositioned) {
element._madePositioned = undefined;
element.style.position =
element.style.top =
element.style.left =
element.style.bottom =
element.style.right = '';
}
return element;
},
/**
* Element.makeClipping(@element) -> Element
*
* Simulates the poorly-supported CSS `clip` property by setting `element`'s
* `overflow` value to `hidden`.
**/
makeClipping: function(element) {
element = $(element);
if (element._overflow) return element;
element._overflow = Element.getStyle(element, 'overflow') || 'auto';
if (element._overflow !== 'hidden')
element.style.overflow = 'hidden';
return element;
},
/**
* Element.undoClipping(@element) -> Element
*
* Sets `element`'s CSS `overflow` property back to the value it had
* _before_ [[Element.makeClipping]] was applied.
**/
undoClipping: function(element) {
element = $(element);
if (!element._overflow) return element;
element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
element._overflow = null;
return element;
},
/**
* Element.cumulativeOffset(@element) -> Array
*
* Returns the offsets of `element` from the top left corner of the
* document.
*
* Returns an array in the form of `[leftValue, topValue]`. Also accessible
* as properties: `{ left: leftValue, top: topValue }`.
**/
cumulativeOffset: function(element) {
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return Element._returnOffset(valueL, valueT);
},
/**
* Element.positionedOffset(@element) -> Array
*
* Returns `element`'s offset relative to its closest positioned ancestor