/
dom.js
3470 lines (3170 loc) · 111 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
(function(GLOBAL) {
var UNDEFINED;
var SLICE = Array.prototype.slice;
// Try to reuse the same created element as much as possible. We'll use
// this DIV for capability checks (where possible) and for normalizing
// HTML content.
var DIV = document.createElement('div');
/** section: DOM
* class Element
**/
/** 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.
*
* ##### More Information
*
* The [[$]] function is the cornerstone of Prototype. Not only does it
* provide a handy alias for `document.getElementById`, it also lets you pass
* indifferently IDs (strings) or DOM node references to your functions:
*
* function foo(element) {
* element = $(element);
* // rest of the function...
* }
*
* Code written this way is flexible — you can pass it the ID of the element
* or the element itself without any type sniffing.
*
* Invoking it with only one argument returns the [[Element]], while invoking it
* with multiple arguments returns an [[Array]] of [[Element]]s (and this
* works recursively: if you're twisted, you could pass it an array
* containing some arrays, and so forth). As this is dependent on
* `getElementById`, [W3C specs](http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-getElBId)
* apply: nonexistent IDs will yield `null` and IDs present multiple times in
* the DOM will yield erratic results. *If you're assigning the same ID to
* multiple elements, you're doing it wrong!*
*
* The function also *extends every returned element* with [[Element.extend]]
* so you can use Prototype's DOM extensions on it. In the following code,
* the two lines are equivalent. However, the second one feels significantly
* more object-oriented:
*
* // Note quite OOP-like...
* Element.hide('itemId');
* // A cleaner feel, thanks to guaranted extension
* $('itemId').hide();
*
* However, when using iterators, leveraging the [[$]] function makes for
* more elegant, more concise, and also more efficient code:
*
* ['item1', 'item2', 'item3'].each(Element.hide);
* // The better way:
* $('item1', 'item2', 'item3').invoke('hide');
*
* See [How Prototype extends the DOM](http://prototypejs.org/learn/extensions)
* for more info.
**/
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);
}
GLOBAL.$ = $;
// Define the DOM Level 2 node type constants if they're missing.
if (!GLOBAL.Node) GLOBAL.Node = {};
if (!GLOBAL.Node.ELEMENT_NODE) {
Object.extend(GLOBAL.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
});
}
// The cache for all our created elements.
var ELEMENT_CACHE = {};
// For performance reasons, we create new elements by cloning a "blank"
// version of a given element. But sometimes this causes problems. Skip
// the cache if:
// (a) We're creating a SELECT element (troublesome in IE6);
// (b) We're setting the `type` attribute on an INPUT element
// (troublesome in IE9).
function shouldUseCreationCache(tagName, attributes) {
if (tagName === 'select') return false;
if ('type' in attributes) return false;
return true;
}
// IE requires that `name` and `type` attributes be set this way.
var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX = (function(){
try {
var el = document.createElement('<input name="x">');
return el.tagName.toLowerCase() === 'input' && el.name === 'x';
}
catch(err) {
return false;
}
})();
/**
* new Element(tagName[, attributes])
* - tagName (String): The name of the HTML element to create.
* - attributes (Object): An optional group of attribute/value pairs to set on
* the element.
*
* Creates an HTML element with `tagName` as the tag name, optionally with the
* given attributes. This can be markedly more concise than working directly
* with the DOM methods, and takes advantage of Prototype's workarounds for
* various browser issues with certain attributes:
*
* ##### Example
*
* // The old way:
* var a = document.createElement('a');
* a.setAttribute('class', 'foo');
* a.setAttribute('href', '/foo.html');
* a.appendChild(document.createTextNode("Next page"));
*
* // The new way:
* var a = new Element('a', { 'class': 'foo', href: '/foo.html' }).update("Next page");
**/
var oldElement = GLOBAL.Element;
function Element(tagName, attributes) {
attributes = attributes || {};
tagName = tagName.toLowerCase();
if (HAS_EXTENDED_CREATE_ELEMENT_SYNTAX && attributes.name) {
tagName = '<' + tagName + ' name="' + attributes.name + '">';
delete attributes.name;
return Element.writeAttribute(document.createElement(tagName), attributes);
}
if (!ELEMENT_CACHE[tagName])
ELEMENT_CACHE[tagName] = Element.extend(document.createElement(tagName));
var node = shouldUseCreationCache(tagName, attributes) ?
ELEMENT_CACHE[tagName].cloneNode(false) : document.createElement(tagName);
return Element.writeAttribute(node, attributes);
}
GLOBAL.Element = Element;
Object.extend(GLOBAL.Element, oldElement || {});
if (oldElement) GLOBAL.Element.prototype = oldElement.prototype;
/**
* mixin Element.Methods
*
* [[Element.Methods]] is a mixin for DOM elements. The methods of this object
* are accessed through the [[$]] utility or through the [[Element]] object and
* shouldn't be accessed directly.
*
* ##### Examples
*
* Hide the element:
*
* $(element).hide();
*
* Return an [[Enumerable]] of all descendant nodes of the element with the id
* "articles":
*
* $('articles').descendants();
**/
Element.Methods = { ByTag: {}, Simulated: {} };
// Temporary object for holding all our initial element methods. We'll add
// them all at once at the bottom of this file.
var methods = {};
/**
* Element.inspect(@element) -> String
*
* Returns the debug-oriented string representation of `element`.
*
* For more information on `inspect` methods, see [[Object.inspect]].
*
* language: html
* <ul>
* <li id="golden-delicious">Golden Delicious</li>
* <li id="mutsu" class="yummy apple">Mutsu</li>
* <li id="mcintosh" class="yummy">McIntosh</li>
* <li></li>
* </ul>
*
* And the associated JavaScript:
*
* $('golden-delicious').inspect();
* // -> '<li id="golden-delicious">'
*
* $('mutsu').inspect();
* // -> '<li id="mutsu" class="yummy apple">'
*
* $('mutsu').next().inspect();
* // -> '<li>'
**/
var INSPECT_ATTRIBUTES = { id: 'id', className: 'class' };
function inspect(element) {
element = $(element);
var result = '<' + element.tagName.toLowerCase();
var attribute, value;
for (var property in INSPECT_ATTRIBUTES) {
attribute = INSPECT_ATTRIBUTES[property];
value = (element[property] || '').toString();
if (value) result += ' ' + attribute + '=' + value.inspect(true);
}
return result + '>';
}
methods.inspect = inspect;
// VISIBILITY
/**
* Element.visible(@element) -> Boolean
*
* Tells whether `element` is visible (i.e., whether its inline `display`
* CSS property is set to `none`.
*
* ##### Examples
*
* language: html
* <div id="visible"></div>
* <div id="hidden" style="display: none;"></div>
*
* And the associated JavaScript:
*
* $('visible').visible();
* // -> true
*
* $('hidden').visible();
* // -> false
*
* ##### Notes
*
* Styles applied via a CSS stylesheet are _not_ taken into consideration.
* Note that this is not a Prototype limitation, it is a CSS limitation.
*
* language: html
* <style>
* #hidden-by-css {
* display: none;
* }
* </style>
*
* [...]
*
* <div id="hidden-by-css"></div>
*
* And the associated JavaScript:
*
* $('hidden-by-css').visible();
* // -> true
**/
function visible(element) {
return $(element).style.display !== 'none';
}
/**
* Element.toggle(@element[, bool]) -> Element
*
* Toggles the CSS `display` of `element`. Returns `element`.
*
* Switches an element's CSS `display` between `none` and its inherited
* value (usually `block` or `inline`).
*
* By default, `toggle` will switch the display to the opposite of its
* current state, but will use the `bool` argument instead if it's
* provided (`true` to show the element, `false` to hide it).
*
* ##### Examples
*
* <div id="welcome-message">Welcome</div>
* <div id="error-message" style="display:none;">Error</div>
*
* $('welcome-message').toggle();
* // -> Element (and hides div#welcome-message)
*
* $('error-message').toggle();
* // -> Element (and displays div#error-message)
*
* $('error-message').toggle(true);
* // -> Element (and displays div#error-message, no matter what its
* // previous state)
*
* Toggle multiple elements using [[Enumerable#each]]:
*
* ['error-message', 'welcome-message'].each(Element.toggle);
* // -> ['error-message', 'welcome-message']
*
* Toggle multiple elements using [[Enumerable#invoke]]:
*
* $('error-message', 'welcome-message').invoke('toggle');
* // -> [Element, Element]
*
* $('error-message', 'welcome-message').invoke('toggle', false);
* // -> [Element, Element] (and hides both elements, no matter what
* their previous state)
*
*
* ##### Notes
*
* [[Element.toggle]] _cannot_ display elements hidden via CSS stylesheets.
* Note that this is not a Prototype limitation but a consequence of how the
* CSS `display` property works.
*
* <style>
* #hidden-by-css {
* display: none;
* }
* </style>
*
* [...]
*
* <div id="hidden-by-css"></div>
*
* $('hidden-by-css').toggle(); // WON'T WORK!
* // -> Element (div#hidden-by-css is still hidden!)
**/
function toggle(element, bool) {
element = $(element);
if (Object.isUndefined(bool))
bool = !Element.visible(element);
Element[bool ? 'show' : 'hide'](element);
return element;
}
/**
* Element.hide(@element) -> Element
*
* Sets `display: none` on `element`. Returns `element`.
*
* ##### Examples
*
* Hide a single element:
*
* <div id="error-message"></div>
*
* $('error-message').hide();
* // -> Element (and hides div#error-message)
*
* Hide multiple elements using [[Enumerable#each]]:
*
* ['content', 'navigation', 'footer'].each(Element.hide);
* // -> ['content', 'navigation', 'footer']
*
* Hide multiple elements using [[Enumerable#invoke]]:
*
* $('content', 'navigation', 'footer').invoke('hide');
* // -> [Element, Element, Element]
**/
function hide(element) {
element = $(element);
element.style.display = 'none';
return element;
}
/**
* Element.show(@element) -> Element
*
* Removes `display: none` on `element`. Returns `element`.
*
* ##### Examples
*
* Show a single element:
*
* <div id="error-message" style="display:none;"></div>
*
* $('error-message').show();
* // -> Element (and displays div#error-message)
*
* Show multiple elements using [[Enumerable#each]]:
*
* ['content', 'navigation', 'footer'].each(Element.show);
* // -> ['content', 'navigation', 'footer']
*
* Show multiple elements using [[Enumerable#invoke]]:
*
* $('content', 'navigation', 'footer').invoke('show');
* // -> [Element, Element, Element]
*
* ##### Notes
*
* [[Element.show]] _cannot_ display elements hidden via CSS stylesheets.
* Note that this is not a Prototype limitation but a consequence of how the
* CSS `display` property works.
*
* <style>
* #hidden-by-css {
* display: none;
* }
* </style>
*
* [...]
*
* <div id="hidden-by-css"></div>
*
* $('hidden-by-css').show(); // DOES NOT WORK!
* // -> Element (div#error-message is still hidden!)
**/
function show(element) {
element = $(element);
element.style.display = '';
return element;
}
Object.extend(methods, {
visible: visible,
toggle: toggle,
hide: hide,
show: show
});
// MANIPULATION
/**
* Element.remove(@element) -> Element
*
* Completely removes `element` from the document and returns it.
*
* If you would rather just hide the element and keep it around for further
* use, try [[Element.hide]] instead.
*
* ##### Examples
*
* language: html
* // Before:
* <ul>
* <li id="golden-delicious">Golden Delicious</li>
* <li id="mutsu">Mutsu</li>
* <li id="mcintosh">McIntosh</li>
* <li id="ida-red">Ida Red</li>
* </ul>
*
* And the associated JavaScript:
*
* $('mutsu').remove();
* // -> Element (and removes li#mutsu)
*
* The resulting HTML:
*
* language: html
* <ul>
* <li id="golden-delicious">Golden Delicious</li>
* <li id="mcintosh">McIntosh</li>
* <li id="ida-red">Ida Red</li>
* </ul>
**/
function remove(element) {
element = $(element);
element.parentNode.removeChild(element);
return element;
}
// 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 LINK_ELEMENT_INNERHTML_BUGGY = (function() {
try {
var el = document.createElement('div');
el.innerHTML = "<link />";
var isBuggy = (el.childNodes.length === 0);
el = null;
return isBuggy;
} catch(e) {
return true;
}
})();
var ANY_INNERHTML_BUGGY = SELECT_ELEMENT_INNERHTML_BUGGY ||
TABLE_ELEMENT_INNERHTML_BUGGY || LINK_ELEMENT_INNERHTML_BUGGY;
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;
})();
/**
* 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.
*
* Note that this method allows seamless content update of table related
* elements in Internet Explorer 6 and beyond.
*
* Any nodes replaced with `Element.update` will first have event
* listeners unregistered and storage keys removed. This frees up memory
* and prevents leaks in certain versions of Internet Explorer. (See
* [[Element.purge]]).
*
* ##### Examples
*
* language: html
* <div id="fruits">carrot, eggplant and cucumber</div>
*
* Passing a regular string:
*
* $('fruits').update('kiwi, banana and apple');
* // -> Element
* $('fruits').innerHTML;
* // -> 'kiwi, banana and apple'
*
* Clearing the element's content:
*
* $('fruits').update();
* // -> Element
* $('fruits').innerHTML;
* // -> '' (an empty string)
*
* And now inserting an HTML snippet:
*
* $('fruits').update('<p>Kiwi, banana <em>and</em> apple.</p>');
* // -> Element
* $('fruits').innerHTML;
* // -> '<p>Kiwi, banana <em>and</em> apple.</p>'
*
* ... with a `<script>` tag thrown in:
*
* $('fruits').update('<p>Kiwi, banana <em>and</em> apple.</p><script>alert("updated!")</script>');
* // -> Element (and prints "updated!" in an alert dialog).
* $('fruits').innerHTML;
* // -> '<p>Kiwi, banana <em>and</em> apple.</p>'
*
* Relying on the `toString()` method:
*
* $('fruits').update(123);
* // -> Element
* $('fruits').innerHTML;
* // -> '123'
*
* Finally, you can do some pretty funky stuff by defining your own
* `toString()` method on your custom objects:
*
* var Fruit = Class.create({
* initialize: function(fruit){
* this.fruit = fruit;
* },
* toString: function(){
* return 'I am a fruit and my name is "' + this.fruit + '".';
* }
* });
* var apple = new Fruit('apple');
*
* $('fruits').update(apple);
* $('fruits').innerHTML;
* // -> 'I am a fruit and my name is "apple".'
**/
function update(element, content) {
element = $(element);
// Purge the element's existing contents of all storage keys and
// event listeners, since said content will be replaced no matter
// what.
var descendants = element.getElementsByTagName('*'),
i = descendants.length;
while (i--) purgeElement(descendants[i]);
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 a SCRIPT element.
element.text = content;
return element;
}
if (ANY_INNERHTML_BUGGY) {
if (tagName in INSERTION_TRANSLATIONS.tags) {
while (element.firstChild)
element.removeChild(element.firstChild);
var nodes = getContentFromAnonymousElement(tagName, content.stripScripts());
for (var i = 0, node; node = nodes[i]; i++)
element.appendChild(node);
} else if (LINK_ELEMENT_INNERHTML_BUGGY && Object.isString(content) && content.indexOf('<link') > -1) {
// IE barfs when inserting a string that beings with a LINK
// element. The workaround is to add any content to the beginning
// of the string; we'll be inserting a text node (see
// getContentFromAnonymousElement below).
while (element.firstChild)
element.removeChild(element.firstChild);
var nodes = getContentFromAnonymousElement(tagName,
content.stripScripts(), true);
for (var i = 0, node; node = nodes[i]; i++)
element.appendChild(node);
} else {
element.innerHTML = content.stripScripts();
}
} else {
element.innerHTML = content.stripScripts();
}
content.evalScripts.bind(content).defer();
return element;
}
/**
* 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.
*
* `newContent` can be either plain text, an HTML snippet or any JavaScript
* object which has a `toString()` method.
*
* If `newContent` contains any `<script>` tags, these will be evaluated
* after `element` has been replaced ([[Element.replace]] internally calls
* [[String#evalScripts]]).
*
* Note that if no argument is provided, [[Element.replace]] will simply
* clear `element` of its content. However, using [[Element.remove]] to do so
* is both faster and more standard compliant.
*
* ##### Examples
*
* language: html
* <div id="food">
* <div id="fruits">
* <p id="first">Kiwi, banana <em>and</em> apple.</p>
* </div>
* </div>
*
* Passing an HTML snippet:
*
* $('first').replace('<ul id="favorite"><li>kiwi</li><li>banana</li><li>apple</li></ul>');
* // -> Element (p#first)
*
* $('fruits').innerHTML;
* // -> '<ul id="favorite"><li>kiwi</li><li>banana</li><li>apple</li></ul>'
*
* Again, with a `<script>` tag thrown in:
*
* $('favorite').replace('<p id="still-first">Melon, oranges <em>and</em> grapes.</p><script>alert("removed!")</script>');
* // -> Element (ul#favorite) and prints "removed!" in an alert dialog.
*
* $('fruits').innerHTML;
* // -> '<p id="still-first">Melon, oranges <em>and</em> grapes.</p>'
*
* With plain text:
*
* $('still-first').replace('Melon, oranges and grapes.');
* // -> Element (p#still-first)
*
* $('fruits').innerHTML;
* // -> 'Melon, oranges and grapes.'
*
* Finally, relying on the `toString()` method:
*
* $('fruits').replace(123);
* // -> Element
*
* $('food').innerHTML;
* // -> '123'
*
* ##### Warning
*
* Using [[Element.replace]] as an instance method (e.g.,
* `$('foo').replace('<p>Bar</p>')`) causes errors in Opera 9 when used on
* `input` elements. The `replace` property is reserved on `input` elements
* as part of [Web Forms 2](http://www.whatwg.org/specs/web-forms/current-work/).
* As a workaround, use the generic version instead
* (`Element.replace('foo', '<p>Bar</p>')`).
*
**/
function replace(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;
}
var INSERTION_TRANSLATIONS = {
before: function(element, node) {
element.parentNode.insertBefore(node, element);
},
top: function(element, node) {
element.insertBefore(node, element.firstChild);
},
bottom: function(element, node) {
element.appendChild(node);
},
after: function(element, node) {
element.parentNode.insertBefore(node, element.nextSibling);
},
tags: {
TABLE: ['<table>', '</table>', 1],
TBODY: ['<table><tbody>', '</tbody></table>', 2],
TR: ['<table><tbody><tr>', '</tr></tbody></table>', 3],
TD: ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
SELECT: ['<select>', '</select>', 1]
}
};
var tags = INSERTION_TRANSLATIONS.tags;
Object.extend(tags, {
THEAD: tags.TBODY,
TFOOT: tags.TBODY,
TH: tags.TD
});
function replace_IE(element, content) {
element = $(element);
if (content && content.toElement)
content = content.toElement();
if (Object.isElement(content)) {
element.parentNode.replaceChild(content, element);
return element;
}
content = Object.toHTML(content);
var parent = element.parentNode, tagName = parent.tagName.toUpperCase();
if (tagName in INSERTION_TRANSLATIONS.tags) {
var nextSibling = Element.next(element);
var fragments = getContentFromAnonymousElement(
tagName, content.stripScripts());
parent.removeChild(element);
var iterator;
if (nextSibling)
iterator = function(node) { parent.insertBefore(node, nextSibling) };
else
iterator = function(node) { parent.appendChild(node); }
fragments.each(iterator);
} else {
// We don't need to special-case this one.
element.outerHTML = content.stripScripts();
}
content.evalScripts.bind(content).defer();
return element;
}
if ('outerHTML' in document.documentElement)
replace = replace_IE;
function isContent(content) {
if (Object.isUndefined(content) || content === null) return false;
if (Object.isString(content) || Object.isNumber(content)) return true;
if (Object.isElement(content)) return true;
if (content.toElement || content.toHTML) return true;
return false;
}
// This private method does the bulk of the work for Element#insert. The
// actual insert method handles argument normalization and multiple
// content insertions.
function insertContentAt(element, content, position) {
position = position.toLowerCase();
var method = INSERTION_TRANSLATIONS[position];
if (content && content.toElement) content = content.toElement();
if (Object.isElement(content)) {
method(element, content);
return element;
}
content = Object.toHTML(content);
var tagName = ((position === 'before' || position === 'after') ?
element.parentNode : element).tagName.toUpperCase();
var childNodes = getContentFromAnonymousElement(tagName, content.stripScripts());
if (position === 'top' || position === 'after') childNodes.reverse();
for (var i = 0, node; node = childNodes[i]; i++)
method(element, node);
content.evalScripts.bind(content).defer();
}
/**
* 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)
*
* Note that if the inserted HTML contains any `<script>` tag, these will be
* automatically evaluated after the insertion (`insert` internally calls
* [[String.evalScripts]] when inserting HTML).
*
* <h5>Examples</h5>
*
* 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>"
* });
**/
function insert(element, insertions) {
element = $(element);
if (isContent(insertions))
insertions = { bottom: insertions };
for (var position in insertions)
insertContentAt(element, insertions[position], position);
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.
*
* If the given element exists on the page, [[Element.wrap]] will wrap it in
* place — its position will remain the same.
*
* The `wrapper` argument can be _either_ an existing [[Element]] _or_ a
* string representing the tag name of an element to be created. The optional
* `attributes` argument can contain a list of attribute/value pairs that
* will be set on the wrapper using [[Element.writeAttribute]].
*
* ##### Examples
*
* Original HTML:
*
* language: html
* <table id="data">
* <tr>
* <th>Foo</th>
* <th>Bar</th>
* </tr>
* <tr>
* <td>1</td>
* <td>2</td>
* </tr>
* </table>
*
* JavaScript:
*
* // approach 1:
* var div = new Element('div', { 'class': 'table-wrapper' });
* $('data').wrap(div);
*
* // approach 2:
* $('data').wrap('div', { 'class': 'table-wrapper' });
*
* // Both examples are equivalent — they return the DIV.
*
* Resulting HTML:
*
* language: html
* <div class="table-wrapper">
* <table id="data">
* <tr>
* <th>Foo</th>
* <th>Bar</th>
* </tr>