bug 6158; fixing replaceWith from throwing errors on non existant elements
[jquery.git] / test / unit / manipulation.js
1 module("manipulation", { teardown: moduleTeardown });
2
3 // Ensure that an extended Array prototype doesn't break jQuery
4 Array.prototype.arrayProtoFn = function(arg) { throw("arrayProtoFn should not be called"); };
5
6 var bareObj = function(value) { return value; };
7 var functionReturningObj = function(value) { return (function() { return value; }); };
8
9 test("text()", function() {
10         expect(2);
11         var expected = "This link has class=\"blog\": Simon Willison's Weblog";
12         equals( jQuery('#sap').text(), expected, 'Check for merged text of more then one element.' );
13
14         // Check serialization of text values
15         equals( jQuery(document.createTextNode("foo")).text(), "foo", "Text node was retreived from .text()." );
16 });
17
18 var testText = function(valueObj) {
19         expect(4);
20         var val = valueObj("<div><b>Hello</b> cruel world!</div>");
21         equals( jQuery("#foo").text(val)[0].innerHTML.replace(/>/g, "&gt;"), "&lt;div&gt;&lt;b&gt;Hello&lt;/b&gt; cruel world!&lt;/div&gt;", "Check escaped text" );
22
23         // using contents will get comments regular, text, and comment nodes
24         var j = jQuery("#nonnodes").contents();
25         j.text(valueObj("hi!"));
26         equals( jQuery(j[0]).text(), "hi!", "Check node,textnode,comment with text()" );
27         equals( j[1].nodeValue, " there ", "Check node,textnode,comment with text()" );
28
29         // Blackberry 4.6 doesn't maintain comments in the DOM
30         equals( jQuery("#nonnodes")[0].childNodes.length < 3 ? 8 : j[2].nodeType, 8, "Check node,textnode,comment with text()" );
31 }
32
33 test("text(String)", function() {
34         testText(bareObj)
35 });
36
37 test("text(Function)", function() {
38         testText(functionReturningObj);
39 });
40
41 test("text(Function) with incoming value", function() {
42         expect(2);
43
44         var old = "This link has class=\"blog\": Simon Willison's Weblog";
45
46         jQuery('#sap').text(function(i, val) {
47                 equals( val, old, "Make sure the incoming value is correct." );
48                 return "foobar";
49         });
50
51         equals( jQuery("#sap").text(), "foobar", 'Check for merged text of more then one element.' );
52
53         QUnit.reset();
54 });
55
56 var testWrap = function(val) {
57         expect(19);
58         var defaultText = 'Try them out:'
59         var result = jQuery('#first').wrap(val( '<div class="red"><span></span></div>' )).text();
60         equals( defaultText, result, 'Check for wrapping of on-the-fly html' );
61         ok( jQuery('#first').parent().parent().is('.red'), 'Check if wrapper has class "red"' );
62
63         QUnit.reset();
64         var defaultText = 'Try them out:'
65         var result = jQuery('#first').wrap(val( document.getElementById('empty') )).parent();
66         ok( result.is('ol'), 'Check for element wrapping' );
67         equals( result.text(), defaultText, 'Check for element wrapping' );
68
69         QUnit.reset();
70         jQuery('#check1').click(function() {
71                 var checkbox = this;
72                 ok( checkbox.checked, "Checkbox's state is erased after wrap() action, see #769" );
73                 jQuery(checkbox).wrap(val( '<div id="c1" style="display:none;"></div>' ));
74                 ok( checkbox.checked, "Checkbox's state is erased after wrap() action, see #769" );
75         }).click();
76
77         // using contents will get comments regular, text, and comment nodes
78         var j = jQuery("#nonnodes").contents();
79         j.wrap(val( "<i></i>" ));
80
81         // Blackberry 4.6 doesn't maintain comments in the DOM
82         equals( jQuery("#nonnodes > i").length, jQuery("#nonnodes")[0].childNodes.length, "Check node,textnode,comment wraps ok" );
83         equals( jQuery("#nonnodes > i").text(), j.text(), "Check node,textnode,comment wraps doesn't hurt text" );
84
85         // Try wrapping a disconnected node
86         var cacheLength = 0;
87         for (var i in jQuery.cache) {
88                 cacheLength++;
89         }
90
91         j = jQuery("<label/>").wrap(val( "<li/>" ));
92         equals( j[0].nodeName.toUpperCase(), "LABEL", "Element is a label" );
93         equals( j[0].parentNode.nodeName.toUpperCase(), "LI", "Element has been wrapped" );
94
95         for (i in jQuery.cache) {
96                 cacheLength--;
97         }
98         equals(cacheLength, 0, "No memory leak in jQuery.cache (bug #7165)");
99
100         // Wrap an element containing a text node
101         j = jQuery("<span/>").wrap("<div>test</div>");
102         equals( j[0].previousSibling.nodeType, 3, "Make sure the previous node is a text element" );
103         equals( j[0].parentNode.nodeName.toUpperCase(), "DIV", "And that we're in the div element." );
104
105         // Try to wrap an element with multiple elements (should fail)
106         j = jQuery("<div><span></span></div>").children().wrap("<p></p><div></div>");
107         equals( j[0].parentNode.parentNode.childNodes.length, 1, "There should only be one element wrapping." );
108         equals( j.length, 1, "There should only be one element (no cloning)." );
109         equals( j[0].parentNode.nodeName.toUpperCase(), "P", "The span should be in the paragraph." );
110
111         // Wrap an element with a jQuery set
112         j = jQuery("<span/>").wrap(jQuery("<div></div>"));
113         equals( j[0].parentNode.nodeName.toLowerCase(), "div", "Wrapping works." );
114
115         // Wrap an element with a jQuery set and event
116         result = jQuery("<div></div>").click(function(){
117                 ok(true, "Event triggered.");
118
119                 // Remove handlers on detached elements
120                 result.unbind();
121                 jQuery(this).unbind();
122         });
123
124         j = jQuery("<span/>").wrap(result);
125         equals( j[0].parentNode.nodeName.toLowerCase(), "div", "Wrapping works." );
126
127         j.parent().trigger("click");
128
129         // clean up attached elements
130         QUnit.reset();
131 }
132
133 test("wrap(String|Element)", function() {
134         testWrap(bareObj);
135 });
136
137 test("wrap(Function)", function() {
138         testWrap(functionReturningObj);
139 })
140
141 var testWrapAll = function(val) {
142         expect(8);
143         var prev = jQuery("#firstp")[0].previousSibling;
144         var p = jQuery("#firstp,#first")[0].parentNode;
145
146         var result = jQuery('#firstp,#first').wrapAll(val( '<div class="red"><div class="tmp"></div></div>' ));
147         equals( result.parent().length, 1, 'Check for wrapping of on-the-fly html' );
148         ok( jQuery('#first').parent().parent().is('.red'), 'Check if wrapper has class "red"' );
149         ok( jQuery('#firstp').parent().parent().is('.red'), 'Check if wrapper has class "red"' );
150         equals( jQuery("#first").parent().parent()[0].previousSibling, prev, "Correct Previous Sibling" );
151         equals( jQuery("#first").parent().parent()[0].parentNode, p, "Correct Parent" );
152
153         QUnit.reset();
154         var prev = jQuery("#firstp")[0].previousSibling;
155         var p = jQuery("#first")[0].parentNode;
156         var result = jQuery('#firstp,#first').wrapAll(val( document.getElementById('empty') ));
157         equals( jQuery("#first").parent()[0], jQuery("#firstp").parent()[0], "Same Parent" );
158         equals( jQuery("#first").parent()[0].previousSibling, prev, "Correct Previous Sibling" );
159         equals( jQuery("#first").parent()[0].parentNode, p, "Correct Parent" );
160 }
161
162 test("wrapAll(String|Element)", function() {
163         testWrapAll(bareObj);
164 });
165
166 var testWrapInner = function(val) {
167         expect(11);
168         var num = jQuery("#first").children().length;
169         var result = jQuery('#first').wrapInner(val('<div class="red"><div id="tmp"></div></div>'));
170         equals( jQuery("#first").children().length, 1, "Only one child" );
171         ok( jQuery("#first").children().is(".red"), "Verify Right Element" );
172         equals( jQuery("#first").children().children().children().length, num, "Verify Elements Intact" );
173
174         QUnit.reset();
175         var num = jQuery("#first").html("foo<div>test</div><div>test2</div>").children().length;
176         var result = jQuery('#first').wrapInner(val('<div class="red"><div id="tmp"></div></div>'));
177         equals( jQuery("#first").children().length, 1, "Only one child" );
178         ok( jQuery("#first").children().is(".red"), "Verify Right Element" );
179         equals( jQuery("#first").children().children().children().length, num, "Verify Elements Intact" );
180
181         QUnit.reset();
182         var num = jQuery("#first").children().length;
183         var result = jQuery('#first').wrapInner(val(document.getElementById('empty')));
184         equals( jQuery("#first").children().length, 1, "Only one child" );
185         ok( jQuery("#first").children().is("#empty"), "Verify Right Element" );
186         equals( jQuery("#first").children().children().length, num, "Verify Elements Intact" );
187
188         var div = jQuery("<div/>");
189         div.wrapInner(val("<span></span>"));
190         equals(div.children().length, 1, "The contents were wrapped.");
191         equals(div.children()[0].nodeName.toLowerCase(), "span", "A span was inserted.");
192 }
193
194 test("wrapInner(String|Element)", function() {
195         testWrapInner(bareObj);
196 });
197
198 test("wrapInner(Function)", function() {
199         testWrapInner(functionReturningObj)
200 });
201
202 test("unwrap()", function() {
203         expect(9);
204
205         jQuery("body").append('  <div id="unwrap" style="display: none;"> <div id="unwrap1"> <span class="unwrap">a</span> <span class="unwrap">b</span> </div> <div id="unwrap2"> <span class="unwrap">c</span> <span class="unwrap">d</span> </div> <div id="unwrap3"> <b><span class="unwrap unwrap3">e</span></b> <b><span class="unwrap unwrap3">f</span></b> </div> </div>');
206
207         var abcd = jQuery('#unwrap1 > span, #unwrap2 > span').get(),
208                 abcdef = jQuery('#unwrap span').get();
209
210         equals( jQuery('#unwrap1 span').add('#unwrap2 span:first').unwrap().length, 3, 'make #unwrap1 and #unwrap2 go away' );
211         same( jQuery('#unwrap > span').get(), abcd, 'all four spans should still exist' );
212
213         same( jQuery('#unwrap3 span').unwrap().get(), jQuery('#unwrap3 > span').get(), 'make all b in #unwrap3 go away' );
214
215         same( jQuery('#unwrap3 span').unwrap().get(), jQuery('#unwrap > span.unwrap3').get(), 'make #unwrap3 go away' );
216
217         same( jQuery('#unwrap').children().get(), abcdef, '#unwrap only contains 6 child spans' );
218
219         same( jQuery('#unwrap > span').unwrap().get(), jQuery('body > span.unwrap').get(), 'make the 6 spans become children of body' );
220
221         same( jQuery('body > span.unwrap').unwrap().get(), jQuery('body > span.unwrap').get(), 'can\'t unwrap children of body' );
222         same( jQuery('body > span.unwrap').unwrap().get(), abcdef, 'can\'t unwrap children of body' );
223
224         same( jQuery('body > span.unwrap').get(), abcdef, 'body contains 6 .unwrap child spans' );
225
226         jQuery('body > span.unwrap').remove();
227 });
228
229 var testAppend = function(valueObj) {
230         expect(37);
231         var defaultText = 'Try them out:'
232         var result = jQuery('#first').append(valueObj('<b>buga</b>'));
233         equals( result.text(), defaultText + 'buga', 'Check if text appending works' );
234         equals( jQuery('#select3').append(valueObj('<option value="appendTest">Append Test</option>')).find('option:last-child').attr('value'), 'appendTest', 'Appending html options to select element');
235
236         QUnit.reset();
237         var expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:";
238         jQuery('#sap').append(valueObj(document.getElementById('first')));
239         equals( jQuery('#sap').text(), expected, "Check for appending of element" );
240
241         QUnit.reset();
242         expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo";
243         jQuery('#sap').append(valueObj([document.getElementById('first'), document.getElementById('yahoo')]));
244         equals( jQuery('#sap').text(), expected, "Check for appending of array of elements" );
245
246         QUnit.reset();
247         expected = "This link has class=\"blog\": Simon Willison's WeblogYahooTry them out:";
248         jQuery('#sap').append(valueObj(jQuery("#yahoo, #first")));
249         equals( jQuery('#sap').text(), expected, "Check for appending of jQuery object" );
250
251         QUnit.reset();
252         jQuery("#sap").append(valueObj( 5 ));
253         ok( jQuery("#sap")[0].innerHTML.match( /5$/ ), "Check for appending a number" );
254
255         QUnit.reset();
256         jQuery("#sap").append(valueObj( " text with spaces " ));
257         ok( jQuery("#sap")[0].innerHTML.match(/ text with spaces $/), "Check for appending text with spaces" );
258
259         QUnit.reset();
260         ok( jQuery("#sap").append(valueObj( [] )), "Check for appending an empty array." );
261         ok( jQuery("#sap").append(valueObj( "" )), "Check for appending an empty string." );
262         ok( jQuery("#sap").append(valueObj( document.getElementsByTagName("foo") )), "Check for appending an empty nodelist." );
263
264         QUnit.reset();
265         jQuery("form").append(valueObj('<input name="radiotest" type="radio" checked="checked" />'));
266         jQuery("form input[name=radiotest]").each(function(){
267                 ok( jQuery(this).is(':checked'), "Append checked radio");
268         }).remove();
269
270         QUnit.reset();
271         jQuery("form").append(valueObj('<input name="radiotest" type="radio" checked    =   \'checked\' />'));
272         jQuery("form input[name=radiotest]").each(function(){
273                 ok( jQuery(this).is(':checked'), "Append alternately formated checked radio");
274         }).remove();
275
276         QUnit.reset();
277         jQuery("form").append(valueObj('<input name="radiotest" type="radio" checked />'));
278         jQuery("form input[name=radiotest]").each(function(){
279                 ok( jQuery(this).is(':checked'), "Append HTML5-formated checked radio");
280         }).remove();
281
282         QUnit.reset();
283         jQuery("#sap").append(valueObj( document.getElementById('form') ));
284         equals( jQuery("#sap>form").size(), 1, "Check for appending a form" ); // Bug #910
285
286         QUnit.reset();
287         var pass = true;
288         try {
289                 var body = jQuery("#iframe")[0].contentWindow.document.body;
290
291                 pass = false;
292                 jQuery( body ).append(valueObj( "<div>test</div>" ));
293                 pass = true;
294         } catch(e) {}
295
296         ok( pass, "Test for appending a DOM node to the contents of an IFrame" );
297
298         QUnit.reset();
299         jQuery('<fieldset/>').appendTo('#form').append(valueObj( '<legend id="legend">test</legend>' ));
300         t( 'Append legend', '#legend', ['legend'] );
301
302         QUnit.reset();
303         jQuery('#select1').append(valueObj( '<OPTION>Test</OPTION>' ));
304         equals( jQuery('#select1 option:last').text(), "Test", "Appending &lt;OPTION&gt; (all caps)" );
305
306         jQuery('#table').append(valueObj( '<colgroup></colgroup>' ));
307         ok( jQuery('#table colgroup').length, "Append colgroup" );
308
309         jQuery('#table colgroup').append(valueObj( '<col/>' ));
310         ok( jQuery('#table colgroup col').length, "Append col" );
311
312         QUnit.reset();
313         jQuery('#table').append(valueObj( '<caption></caption>' ));
314         ok( jQuery('#table caption').length, "Append caption" );
315
316         QUnit.reset();
317         jQuery('form:last')
318                 .append(valueObj( '<select id="appendSelect1"></select>' ))
319                 .append(valueObj( '<select id="appendSelect2"><option>Test</option></select>' ));
320
321         t( "Append Select", "#appendSelect1, #appendSelect2", ["appendSelect1", "appendSelect2"] );
322
323         equals( "Two nodes", jQuery('<div />').append("Two", " nodes").text(), "Appending two text nodes (#4011)" );
324
325         // using contents will get comments regular, text, and comment nodes
326         var j = jQuery("#nonnodes").contents();
327         var d = jQuery("<div/>").appendTo("#nonnodes").append(j);
328         equals( jQuery("#nonnodes").length, 1, "Check node,textnode,comment append moved leaving just the div" );
329         ok( d.contents().length >= 2, "Check node,textnode,comment append works" );
330         d.contents().appendTo("#nonnodes");
331         d.remove();
332         ok( jQuery("#nonnodes").contents().length >= 2, "Check node,textnode,comment append cleanup worked" );
333 }
334
335 test("append(String|Element|Array&lt;Element&gt;|jQuery)", function() {
336         testAppend(bareObj);
337 });
338
339 test("append(Function)", function() {
340         testAppend(functionReturningObj);
341 });
342
343 test("append(Function) with incoming value", function() {
344         expect(12);
345
346         var defaultText = 'Try them out:', old = jQuery("#first").html();
347
348         var result = jQuery('#first').append(function(i, val){
349                 equals( val, old, "Make sure the incoming value is correct." );
350                 return '<b>buga</b>';
351         });
352         equals( result.text(), defaultText + 'buga', 'Check if text appending works' );
353
354         var select = jQuery('#select3');
355         old = select.html();
356
357         equals( select.append(function(i, val){
358                 equals( val, old, "Make sure the incoming value is correct." );
359                 return '<option value="appendTest">Append Test</option>';
360         }).find('option:last-child').attr('value'), 'appendTest', 'Appending html options to select element');
361
362         QUnit.reset();
363         var expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:";
364         old = jQuery("#sap").html();
365
366         jQuery('#sap').append(function(i, val){
367                 equals( val, old, "Make sure the incoming value is correct." );
368                 return document.getElementById('first');
369         });
370         equals( jQuery('#sap').text(), expected, "Check for appending of element" );
371
372         QUnit.reset();
373         expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo";
374         old = jQuery("#sap").html();
375
376         jQuery('#sap').append(function(i, val){
377                 equals( val, old, "Make sure the incoming value is correct." );
378                 return [document.getElementById('first'), document.getElementById('yahoo')];
379         });
380         equals( jQuery('#sap').text(), expected, "Check for appending of array of elements" );
381
382         QUnit.reset();
383         expected = "This link has class=\"blog\": Simon Willison's WeblogYahooTry them out:";
384         old = jQuery("#sap").html();
385
386         jQuery('#sap').append(function(i, val){
387                 equals( val, old, "Make sure the incoming value is correct." );
388                 return jQuery("#yahoo, #first");
389         });
390         equals( jQuery('#sap').text(), expected, "Check for appending of jQuery object" );
391
392         QUnit.reset();
393         old = jQuery("#sap").html();
394
395         jQuery("#sap").append(function(i, val){
396                 equals( val, old, "Make sure the incoming value is correct." );
397                 return 5;
398         });
399         ok( jQuery("#sap")[0].innerHTML.match( /5$/ ), "Check for appending a number" );
400
401         QUnit.reset();
402 });
403
404 test("append the same fragment with events (Bug #6997, 5566)", function () {
405         var doExtra = !jQuery.support.noCloneEvent && document.fireEvent;
406         expect(2 + (doExtra ? 1 : 0));
407         stop(1000);
408
409         var element;
410
411         // This patch modified the way that cloning occurs in IE; we need to make sure that
412         // native event handlers on the original object don't get disturbed when they are
413         // modified on the clone
414         if ( doExtra ) {
415                 element = jQuery("div:first").click(function () {
416                         ok(true, "Event exists on original after being unbound on clone");
417                         jQuery(this).unbind('click');
418                 });
419                 var clone = element.clone(true).unbind('click');
420                 clone[0].fireEvent('onclick');
421                 element[0].fireEvent('onclick');
422
423                 // manually clean up detached elements
424                 clone.remove();
425         }
426
427         element = jQuery("<a class='test6997'></a>").click(function () {
428                 ok(true, "Append second element events work");
429         });
430
431         jQuery("#listWithTabIndex li").append(element)
432                 .find('a.test6997').eq(1).click();
433
434         element = jQuery("<li class='test6997'></li>").click(function () {
435                 ok(true, "Before second element events work");
436                 start();
437         });
438
439         jQuery("#listWithTabIndex li").before(element);
440         jQuery("#listWithTabIndex li.test6997").eq(1).click();
441 });
442
443 test("appendTo(String|Element|Array&lt;Element&gt;|jQuery)", function() {
444         expect(16);
445
446         var defaultText = 'Try them out:'
447         jQuery('<b>buga</b>').appendTo('#first');
448         equals( jQuery("#first").text(), defaultText + 'buga', 'Check if text appending works' );
449         equals( jQuery('<option value="appendTest">Append Test</option>').appendTo('#select3').parent().find('option:last-child').attr('value'), 'appendTest', 'Appending html options to select element');
450
451         QUnit.reset();
452         var l = jQuery("#first").children().length + 2;
453         jQuery("<strong>test</strong>");
454         jQuery("<strong>test</strong>");
455         jQuery([ jQuery("<strong>test</strong>")[0], jQuery("<strong>test</strong>")[0] ])
456                 .appendTo("#first");
457         equals( jQuery("#first").children().length, l, "Make sure the elements were inserted." );
458         equals( jQuery("#first").children().last()[0].nodeName.toLowerCase(), "strong", "Verify the last element." );
459
460         QUnit.reset();
461         var expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:";
462         jQuery(document.getElementById('first')).appendTo('#sap');
463         equals( jQuery('#sap').text(), expected, "Check for appending of element" );
464
465         QUnit.reset();
466         expected = "This link has class=\"blog\": Simon Willison's WeblogTry them out:Yahoo";
467         jQuery([document.getElementById('first'), document.getElementById('yahoo')]).appendTo('#sap');
468         equals( jQuery('#sap').text(), expected, "Check for appending of array of elements" );
469
470         QUnit.reset();
471         ok( jQuery(document.createElement("script")).appendTo("body").length, "Make sure a disconnected script can be appended." );
472
473         QUnit.reset();
474         expected = "This link has class=\"blog\": Simon Willison's WeblogYahooTry them out:";
475         jQuery("#yahoo, #first").appendTo('#sap');
476         equals( jQuery('#sap').text(), expected, "Check for appending of jQuery object" );
477
478         QUnit.reset();
479         jQuery('#select1').appendTo('#foo');
480         t( 'Append select', '#foo select', ['select1'] );
481
482         QUnit.reset();
483         var div = jQuery("<div/>").click(function(){
484                 ok(true, "Running a cloned click.");
485         });
486         div.appendTo("#main, #moretests");
487
488         jQuery("#main div:last").click();
489         jQuery("#moretests div:last").click();
490
491         QUnit.reset();
492         var div = jQuery("<div/>").appendTo("#main, #moretests");
493
494         equals( div.length, 2, "appendTo returns the inserted elements" );
495
496         div.addClass("test");
497
498         ok( jQuery("#main div:last").hasClass("test"), "appendTo element was modified after the insertion" );
499         ok( jQuery("#moretests div:last").hasClass("test"), "appendTo element was modified after the insertion" );
500
501         QUnit.reset();
502
503         div = jQuery("<div/>");
504         jQuery("<span>a</span><b>b</b>").filter("span").appendTo( div );
505
506         equals( div.children().length, 1, "Make sure the right number of children were inserted." );
507
508         div = jQuery("#moretests div");
509
510         var num = jQuery("#main div").length;
511         div.remove().appendTo("#main");
512
513         equals( jQuery("#main div").length, num, "Make sure all the removed divs were inserted." );
514
515         QUnit.reset();
516 });
517
518 var testPrepend = function(val) {
519         expect(5);
520         var defaultText = 'Try them out:'
521         var result = jQuery('#first').prepend(val( '<b>buga</b>' ));
522         equals( result.text(), 'buga' + defaultText, 'Check if text prepending works' );
523         equals( jQuery('#select3').prepend(val( '<option value="prependTest">Prepend Test</option>' )).find('option:first-child').attr('value'), 'prependTest', 'Prepending html options to select element');
524
525         QUnit.reset();
526         var expected = "Try them out:This link has class=\"blog\": Simon Willison's Weblog";
527         jQuery('#sap').prepend(val( document.getElementById('first') ));
528         equals( jQuery('#sap').text(), expected, "Check for prepending of element" );
529
530         QUnit.reset();
531         expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog";
532         jQuery('#sap').prepend(val( [document.getElementById('first'), document.getElementById('yahoo')] ));
533         equals( jQuery('#sap').text(), expected, "Check for prepending of array of elements" );
534
535         QUnit.reset();
536         expected = "YahooTry them out:This link has class=\"blog\": Simon Willison's Weblog";
537         jQuery('#sap').prepend(val( jQuery("#yahoo, #first") ));
538         equals( jQuery('#sap').text(), expected, "Check for prepending of jQuery object" );
539 };
540
541 test("prepend(String|Element|Array&lt;Element&gt;|jQuery)", function() {
542         testPrepend(bareObj);
543 });
544
545 test("prepend(Function)", function() {
546         testPrepend(functionReturningObj);
547 });
548
549 test("prepend(Function) with incoming value", function() {
550         expect(10);
551
552         var defaultText = 'Try them out:', old = jQuery('#first').html();
553         var result = jQuery('#first').prepend(function(i, val) {
554                 equals( val, old, "Make sure the incoming value is correct." );
555                 return '<b>buga</b>';
556         });
557         equals( result.text(), 'buga' + defaultText, 'Check if text prepending works' );
558
559         old = jQuery("#select3").html();
560
561         equals( jQuery('#select3').prepend(function(i, val) {
562                 equals( val, old, "Make sure the incoming value is correct." );
563                 return '<option value="prependTest">Prepend Test</option>';
564         }).find('option:first-child').attr('value'), 'prependTest', 'Prepending html options to select element');
565
566         QUnit.reset();
567         var expected = "Try them out:This link has class=\"blog\": Simon Willison's Weblog";
568         old = jQuery('#sap').html();
569
570         jQuery('#sap').prepend(function(i, val) {
571                 equals( val, old, "Make sure the incoming value is correct." );
572                 return document.getElementById('first');
573         });
574
575         equals( jQuery('#sap').text(), expected, "Check for prepending of element" );
576
577         QUnit.reset();
578         expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog";
579         old = jQuery('#sap').html();
580
581         jQuery('#sap').prepend(function(i, val) {
582                 equals( val, old, "Make sure the incoming value is correct." );
583                 return [document.getElementById('first'), document.getElementById('yahoo')];
584         });
585
586         equals( jQuery('#sap').text(), expected, "Check for prepending of array of elements" );
587
588         QUnit.reset();
589         expected = "YahooTry them out:This link has class=\"blog\": Simon Willison's Weblog";
590         old = jQuery('#sap').html();
591
592         jQuery('#sap').prepend(function(i, val) {
593                 equals( val, old, "Make sure the incoming value is correct." );
594                 return jQuery("#yahoo, #first");
595         });
596
597         equals( jQuery('#sap').text(), expected, "Check for prepending of jQuery object" );
598 });
599
600 test("prependTo(String|Element|Array&lt;Element&gt;|jQuery)", function() {
601         expect(6);
602         var defaultText = 'Try them out:'
603         jQuery('<b>buga</b>').prependTo('#first');
604         equals( jQuery('#first').text(), 'buga' + defaultText, 'Check if text prepending works' );
605         equals( jQuery('<option value="prependTest">Prepend Test</option>').prependTo('#select3').parent().find('option:first-child').attr('value'), 'prependTest', 'Prepending html options to select element');
606
607         QUnit.reset();
608         var expected = "Try them out:This link has class=\"blog\": Simon Willison's Weblog";
609         jQuery(document.getElementById('first')).prependTo('#sap');
610         equals( jQuery('#sap').text(), expected, "Check for prepending of element" );
611
612         QUnit.reset();
613         expected = "Try them out:YahooThis link has class=\"blog\": Simon Willison's Weblog";
614         jQuery([document.getElementById('first'), document.getElementById('yahoo')]).prependTo('#sap');
615         equals( jQuery('#sap').text(), expected, "Check for prepending of array of elements" );
616
617         QUnit.reset();
618         expected = "YahooTry them out:This link has class=\"blog\": Simon Willison's Weblog";
619         jQuery("#yahoo, #first").prependTo('#sap');
620         equals( jQuery('#sap').text(), expected, "Check for prepending of jQuery object" );
621
622         QUnit.reset();
623         jQuery('<select id="prependSelect1"></select>').prependTo('form:last');
624         jQuery('<select id="prependSelect2"><option>Test</option></select>').prependTo('form:last');
625
626         t( "Prepend Select", "#prependSelect2, #prependSelect1", ["prependSelect2", "prependSelect1"] );
627 });
628
629 var testBefore = function(val) {
630         expect(6);
631         var expected = 'This is a normal link: bugaYahoo';
632         jQuery('#yahoo').before(val( '<b>buga</b>' ));
633         equals( jQuery('#en').text(), expected, 'Insert String before' );
634
635         QUnit.reset();
636         expected = "This is a normal link: Try them out:Yahoo";
637         jQuery('#yahoo').before(val( document.getElementById('first') ));
638         equals( jQuery('#en').text(), expected, "Insert element before" );
639
640         QUnit.reset();
641         expected = "This is a normal link: Try them out:diveintomarkYahoo";
642         jQuery('#yahoo').before(val( [document.getElementById('first'), document.getElementById('mark')] ));
643         equals( jQuery('#en').text(), expected, "Insert array of elements before" );
644
645         QUnit.reset();
646         expected = "This is a normal link: diveintomarkTry them out:Yahoo";
647         jQuery('#yahoo').before(val( jQuery("#mark, #first") ));
648         equals( jQuery('#en').text(), expected, "Insert jQuery before" );
649
650         var set = jQuery("<div/>").before("<span>test</span>");
651         equals( set[0].nodeName.toLowerCase(), "span", "Insert the element before the disconnected node." );
652         equals( set.length, 2, "Insert the element before the disconnected node." );
653 }
654
655 test("before(String|Element|Array&lt;Element&gt;|jQuery)", function() {
656         testBefore(bareObj);
657 });
658
659 test("before(Function)", function() {
660         testBefore(functionReturningObj);
661 })
662
663 test("insertBefore(String|Element|Array&lt;Element&gt;|jQuery)", function() {
664         expect(4);
665         var expected = 'This is a normal link: bugaYahoo';
666         jQuery('<b>buga</b>').insertBefore('#yahoo');
667         equals( jQuery('#en').text(), expected, 'Insert String before' );
668
669         QUnit.reset();
670         expected = "This is a normal link: Try them out:Yahoo";
671         jQuery(document.getElementById('first')).insertBefore('#yahoo');
672         equals( jQuery('#en').text(), expected, "Insert element before" );
673
674         QUnit.reset();
675         expected = "This is a normal link: Try them out:diveintomarkYahoo";
676         jQuery([document.getElementById('first'), document.getElementById('mark')]).insertBefore('#yahoo');
677         equals( jQuery('#en').text(), expected, "Insert array of elements before" );
678
679         QUnit.reset();
680         expected = "This is a normal link: diveintomarkTry them out:Yahoo";
681         jQuery("#mark, #first").insertBefore('#yahoo');
682         equals( jQuery('#en').text(), expected, "Insert jQuery before" );
683 });
684
685 var testAfter = function(val) {
686         expect(6);
687         var expected = 'This is a normal link: Yahoobuga';
688         jQuery('#yahoo').after(val( '<b>buga</b>' ));
689         equals( jQuery('#en').text(), expected, 'Insert String after' );
690
691         QUnit.reset();
692         expected = "This is a normal link: YahooTry them out:";
693         jQuery('#yahoo').after(val( document.getElementById('first') ));
694         equals( jQuery('#en').text(), expected, "Insert element after" );
695
696         QUnit.reset();
697         expected = "This is a normal link: YahooTry them out:diveintomark";
698         jQuery('#yahoo').after(val( [document.getElementById('first'), document.getElementById('mark')] ));
699         equals( jQuery('#en').text(), expected, "Insert array of elements after" );
700
701         QUnit.reset();
702         expected = "This is a normal link: YahoodiveintomarkTry them out:";
703         jQuery('#yahoo').after(val( jQuery("#mark, #first") ));
704         equals( jQuery('#en').text(), expected, "Insert jQuery after" );
705
706         var set = jQuery("<div/>").after("<span>test</span>");
707         equals( set[1].nodeName.toLowerCase(), "span", "Insert the element after the disconnected node." );
708         equals( set.length, 2, "Insert the element after the disconnected node." );
709 };
710
711 test("after(String|Element|Array&lt;Element&gt;|jQuery)", function() {
712         testAfter(bareObj);
713 });
714
715 test("after(Function)", function() {
716         testAfter(functionReturningObj);
717 })
718
719 test("insertAfter(String|Element|Array&lt;Element&gt;|jQuery)", function() {
720         expect(4);
721         var expected = 'This is a normal link: Yahoobuga';
722         jQuery('<b>buga</b>').insertAfter('#yahoo');
723         equals( jQuery('#en').text(), expected, 'Insert String after' );
724
725         QUnit.reset();
726         expected = "This is a normal link: YahooTry them out:";
727         jQuery(document.getElementById('first')).insertAfter('#yahoo');
728         equals( jQuery('#en').text(), expected, "Insert element after" );
729
730         QUnit.reset();
731         expected = "This is a normal link: YahooTry them out:diveintomark";
732         jQuery([document.getElementById('first'), document.getElementById('mark')]).insertAfter('#yahoo');
733         equals( jQuery('#en').text(), expected, "Insert array of elements after" );
734
735         QUnit.reset();
736         expected = "This is a normal link: YahoodiveintomarkTry them out:";
737         jQuery("#mark, #first").insertAfter('#yahoo');
738         equals( jQuery('#en').text(), expected, "Insert jQuery after" );
739 });
740
741 var testReplaceWith = function(val) {
742         expect(21);
743         jQuery('#yahoo').replaceWith(val( '<b id="replace">buga</b>' ));
744         ok( jQuery("#replace")[0], 'Replace element with string' );
745         ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after string' );
746
747         QUnit.reset();
748         jQuery('#yahoo').replaceWith(val( document.getElementById('first') ));
749         ok( jQuery("#first")[0], 'Replace element with element' );
750         ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after element' );
751
752         QUnit.reset();
753         jQuery("#main").append('<div id="bar"><div id="baz">Foo</div></div>');
754         jQuery('#baz').replaceWith("Baz");
755         equals( jQuery("#bar").text(),"Baz", 'Replace element with text' );
756         ok( !jQuery("#baz")[0], 'Verify that original element is gone, after element' );
757
758         QUnit.reset();
759         jQuery('#yahoo').replaceWith(val( [document.getElementById('first'), document.getElementById('mark')] ));
760         ok( jQuery("#first")[0], 'Replace element with array of elements' );
761         ok( jQuery("#mark")[0], 'Replace element with array of elements' );
762         ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after array of elements' );
763
764         QUnit.reset();
765         jQuery('#yahoo').replaceWith(val( jQuery("#mark, #first") ));
766         ok( jQuery("#first")[0], 'Replace element with set of elements' );
767         ok( jQuery("#mark")[0], 'Replace element with set of elements' );
768         ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after set of elements' );
769
770         QUnit.reset();
771         var tmp = jQuery("<div/>").appendTo("body").click(function(){ ok(true, "Newly bound click run." ); });
772         var y = jQuery('<div/>').appendTo("body").click(function(){ ok(true, "Previously bound click run." ); });
773         var child = y.append("<b>test</b>").find("b").click(function(){ ok(true, "Child bound click run." ); return false; });
774
775         y.replaceWith( tmp );
776
777         tmp.click();
778         y.click(); // Shouldn't be run
779         child.click(); // Shouldn't be run
780
781         tmp.remove();
782         y.remove();
783         child.remove();
784
785         QUnit.reset();
786
787         y = jQuery('<div/>').appendTo("body").click(function(){ ok(true, "Previously bound click run." ); });
788         var child2 = y.append("<u>test</u>").find("u").click(function(){ ok(true, "Child 2 bound click run." ); return false; });
789
790         y.replaceWith( child2 );
791
792         child2.click();
793
794         y.remove();
795         child2.remove();
796
797         QUnit.reset();
798
799         var set = jQuery("<div/>").replaceWith(val("<span>test</span>"));
800         equals( set[0].nodeName.toLowerCase(), "span", "Replace the disconnected node." );
801         equals( set.length, 1, "Replace the disconnected node." );
802         
803         var non_existant = jQuery('#does-not-exist').replaceWith( val("<b>should not throw an error</b>") );
804         equals( non_existant.length, 0, "Length of non existant element." )
805
806         var $div = jQuery("<div class='replacewith'></div>").appendTo("body");
807         // TODO: Work on jQuery(...) inline script execution
808         //$div.replaceWith("<div class='replacewith'></div><script>" +
809                 //"equals(jQuery('.replacewith').length, 1, 'Check number of elements in page.');" +
810                 //"</script>");
811         equals(jQuery('.replacewith').length, 1, 'Check number of elements in page.');
812         jQuery('.replacewith').remove();
813
814         QUnit.reset();
815
816         jQuery("#main").append("<div id='replaceWith'></div>");
817         equals( jQuery("#main").find("div[id=replaceWith]").length, 1, "Make sure only one div exists." );
818
819         jQuery("#replaceWith").replaceWith( val("<div id='replaceWith'></div>") );
820         equals( jQuery("#main").find("div[id=replaceWith]").length, 1, "Make sure only one div exists." );
821
822         jQuery("#replaceWith").replaceWith( val("<div id='replaceWith'></div>") );
823         equals( jQuery("#main").find("div[id=replaceWith]").length, 1, "Make sure only one div exists." );
824 }
825
826 test("replaceWith(String|Element|Array&lt;Element&gt;|jQuery)", function() {
827         testReplaceWith(bareObj);
828 });
829
830 test("replaceWith(Function)", function() {
831         testReplaceWith(functionReturningObj);
832
833         expect(22);
834
835         var y = jQuery("#yahoo")[0];
836
837         jQuery(y).replaceWith(function(){
838                 equals( this, y, "Make sure the context is coming in correctly." );
839         });
840
841         QUnit.reset();
842 });
843
844 test("replaceWith(string) for more than one element", function(){
845         expect(3);
846
847         equals(jQuery('#foo p').length, 3, 'ensuring that test data has not changed');
848
849         jQuery('#foo p').replaceWith('<span>bar</span>');
850         equals(jQuery('#foo span').length, 3, 'verify that all the three original element have been replaced');
851         equals(jQuery('#foo p').length, 0, 'verify that all the three original element have been replaced');
852 });
853
854 test("replaceAll(String|Element|Array&lt;Element&gt;|jQuery)", function() {
855         expect(10);
856         jQuery('<b id="replace">buga</b>').replaceAll("#yahoo");
857         ok( jQuery("#replace")[0], 'Replace element with string' );
858         ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after string' );
859
860         QUnit.reset();
861         jQuery(document.getElementById('first')).replaceAll("#yahoo");
862         ok( jQuery("#first")[0], 'Replace element with element' );
863         ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after element' );
864
865         QUnit.reset();
866         jQuery([document.getElementById('first'), document.getElementById('mark')]).replaceAll("#yahoo");
867         ok( jQuery("#first")[0], 'Replace element with array of elements' );
868         ok( jQuery("#mark")[0], 'Replace element with array of elements' );
869         ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after array of elements' );
870
871         QUnit.reset();
872         jQuery("#mark, #first").replaceAll("#yahoo");
873         ok( jQuery("#first")[0], 'Replace element with set of elements' );
874         ok( jQuery("#mark")[0], 'Replace element with set of elements' );
875         ok( !jQuery("#yahoo")[0], 'Verify that original element is gone, after set of elements' );
876 });
877
878 test("jQuery.clone() (#8017)", function() {
879
880         expect(2);
881
882         ok( jQuery.clone && jQuery.isFunction( jQuery.clone ) , "jQuery.clone() utility exists and is a function.");
883
884         var main = jQuery("#main")[0],
885                         clone = jQuery.clone( main );
886
887         equals( main.childNodes.length, clone.childNodes.length, "Simple child length to ensure a large dom tree copies correctly" );
888 });
889
890 test("clone() (#8070)", function () {
891         expect(2);
892
893         jQuery('<select class="test8070"></select><select class="test8070"></select>').appendTo('#main');
894         var selects = jQuery('.test8070');
895         selects.append('<OPTION>1</OPTION><OPTION>2</OPTION>');
896
897         equals( selects[0].childNodes.length, 2, "First select got two nodes" );
898         equals( selects[1].childNodes.length, 2, "Second select got two nodes" );
899
900         selects.remove();
901 });
902
903 test("clone()", function() {
904         expect(37);
905         equals( 'This is a normal link: Yahoo', jQuery('#en').text(), 'Assert text for #en' );
906         var clone = jQuery('#yahoo').clone();
907         equals( 'Try them out:Yahoo', jQuery('#first').append(clone).text(), 'Check for clone' );
908         equals( 'This is a normal link: Yahoo', jQuery('#en').text(), 'Reassert text for #en' );
909
910         var cloneTags = [
911                 "<table/>", "<tr/>", "<td/>", "<div/>",
912                 "<button/>", "<ul/>", "<ol/>", "<li/>",
913                 "<input type='checkbox' />", "<select/>", "<option/>", "<textarea/>",
914                 "<tbody/>", "<thead/>", "<tfoot/>", "<iframe/>"
915         ];
916         for (var i = 0; i < cloneTags.length; i++) {
917                 var j = jQuery(cloneTags[i]);
918                 equals( j[0].tagName, j.clone()[0].tagName, 'Clone a ' + cloneTags[i]);
919         }
920
921         // using contents will get comments regular, text, and comment nodes
922         var cl = jQuery("#nonnodes").contents().clone();
923         ok( cl.length >= 2, "Check node,textnode,comment clone works (some browsers delete comments on clone)" );
924
925         var div = jQuery("<div><ul><li>test</li></ul></div>").click(function(){
926                 ok( true, "Bound event still exists." );
927         });
928
929         clone = div.clone(true);
930
931         // manually clean up detached elements
932         div.remove();
933
934         div = clone.clone(true);
935
936         // manually clean up detached elements
937         clone.remove();
938
939         equals( div.length, 1, "One element cloned" );
940         equals( div[0].nodeName.toUpperCase(), "DIV", "DIV element cloned" );
941         div.trigger("click");
942
943         // manually clean up detached elements
944         div.remove();
945
946         div = jQuery("<div/>").append([ document.createElement("table"), document.createElement("table") ]);
947         div.find("table").click(function(){
948                 ok( true, "Bound event still exists." );
949         });
950
951         clone = div.clone(true);
952         equals( clone.length, 1, "One element cloned" );
953         equals( clone[0].nodeName.toUpperCase(), "DIV", "DIV element cloned" );
954         clone.find("table:last").trigger("click");
955
956         // manually clean up detached elements
957         div.remove();
958         clone.remove();
959
960         var divEvt = jQuery("<div><ul><li>test</li></ul></div>").click(function(){
961                 ok( false, "Bound event still exists after .clone()." );
962         }),
963                 cloneEvt = divEvt.clone();
964
965         // Make sure that doing .clone() doesn't clone events
966         cloneEvt.trigger("click");
967
968         cloneEvt.remove();
969         divEvt.remove();
970
971         // this is technically an invalid object, but because of the special
972         // classid instantiation it is the only kind that IE has trouble with,
973         // so let's test with it too.
974         div = jQuery("<div/>").html('<object height="355" width="425" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">  <param name="movie" value="http://www.youtube.com/v/3KANI2dpXLw&amp;hl=en">  <param name="wmode" value="transparent"> </object>');
975
976         clone = div.clone(true);
977         equals( clone.length, 1, "One element cloned" );
978         equals( clone.html(), div.html(), "Element contents cloned" );
979         equals( clone[0].nodeName.toUpperCase(), "DIV", "DIV element cloned" );
980
981         // and here's a valid one.
982         div = jQuery("<div/>").html('<object height="355" width="425" type="application/x-shockwave-flash" data="http://www.youtube.com/v/3KANI2dpXLw&amp;hl=en">  <param name="movie" value="http://www.youtube.com/v/3KANI2dpXLw&amp;hl=en">  <param name="wmode" value="transparent"> </object>');
983
984         clone = div.clone(true);
985         equals( clone.length, 1, "One element cloned" );
986         equals( clone.html(), div.html(), "Element contents cloned" );
987         equals( clone[0].nodeName.toUpperCase(), "DIV", "DIV element cloned" );
988
989         div = jQuery("<div/>").data({ a: true });
990         clone = div.clone(true);
991         equals( clone.data("a"), true, "Data cloned." );
992         clone.data("a", false);
993         equals( clone.data("a"), false, "Ensure cloned element data object was correctly modified" );
994         equals( div.data("a"), true, "Ensure cloned element data object is copied, not referenced" );
995
996         // manually clean up detached elements
997         div.remove();
998         clone.remove();
999
1000         var form = document.createElement("form");
1001         form.action = "/test/";
1002         var div = document.createElement("div");
1003         div.appendChild( document.createTextNode("test") );
1004         form.appendChild( div );
1005
1006         equals( jQuery(form).clone().children().length, 1, "Make sure we just get the form back." );
1007
1008         equal( jQuery("body").clone().children()[0].id, "qunit-header", "Make sure cloning body works" );
1009 });
1010
1011 test("clone(form element) (Bug #3879, #6655)", function() {
1012         expect(6);
1013         var element = jQuery("<select><option>Foo</option><option selected>Bar</option></select>");
1014
1015         equals( element.clone().find("option:selected").val(), element.find("option:selected").val(), "Selected option cloned correctly" );
1016
1017         element = jQuery("<input type='checkbox' value='foo'>").attr('checked', 'checked');
1018         clone = element.clone();
1019
1020         equals( clone.is(":checked"), element.is(":checked"), "Checked input cloned correctly" );
1021         equals( clone[0].defaultValue, "foo", "Checked input defaultValue cloned correctly" );
1022         equals( clone[0].defaultChecked, !jQuery.support.noCloneChecked, "Checked input defaultChecked cloned correctly" );
1023
1024         element = jQuery("<input type='text' value='foo'>");
1025         clone = element.clone();
1026         equals( clone[0].defaultValue, "foo", "Text input defaultValue cloned correctly" );
1027
1028         element = jQuery("<textarea>foo</textarea>");
1029         clone = element.clone();
1030         equals( clone[0].defaultValue, "foo", "Textarea defaultValue cloned correctly" );
1031 });
1032
1033 test("clone(multiple selected options) (Bug #8129)", function() {
1034         expect(1);
1035         var element = jQuery("<select><option>Foo</option><option selected>Bar</option><option selected>Baz</option></select>");
1036
1037         equals( element.clone().find("option:selected").length, element.find("option:selected").length, "Multiple selected options cloned correctly" );
1038
1039 });
1040
1041 if (!isLocal) {
1042 test("clone() on XML nodes", function() {
1043         expect(2);
1044         stop();
1045         jQuery.get("data/dashboard.xml", function (xml) {
1046                 var root = jQuery(xml.documentElement).clone();
1047                 var origTab = jQuery("tab", xml).eq(0);
1048                 var cloneTab = jQuery("tab", root).eq(0);
1049                 origTab.text("origval");
1050                 cloneTab.text("cloneval");
1051                 equals(origTab.text(), "origval", "Check original XML node was correctly set");
1052                 equals(cloneTab.text(), "cloneval", "Check cloned XML node was correctly set");
1053                 start();
1054         });
1055 });
1056 }
1057
1058 var testHtml = function(valueObj) {
1059         expect(31);
1060
1061         jQuery.scriptorder = 0;
1062
1063         var div = jQuery("#main > div");
1064         div.html(valueObj("<b>test</b>"));
1065         var pass = true;
1066         for ( var i = 0; i < div.size(); i++ ) {
1067                 if ( div.get(i).childNodes.length != 1 ) pass = false;
1068         }
1069         ok( pass, "Set HTML" );
1070
1071         div = jQuery("<div/>").html( valueObj('<div id="parent_1"><div id="child_1"/></div><div id="parent_2"/>') );
1072
1073         equals( div.children().length, 2, "Make sure two child nodes exist." );
1074         equals( div.children().children().length, 1, "Make sure that a grandchild exists." );
1075
1076         var space = jQuery("<div/>").html(valueObj("&#160;"))[0].innerHTML;
1077         ok( /^\xA0$|^&nbsp;$/.test( space ), "Make sure entities are passed through correctly." );
1078         equals( jQuery("<div/>").html(valueObj("&amp;"))[0].innerHTML, "&amp;", "Make sure entities are passed through correctly." );
1079
1080         jQuery("#main").html(valueObj("<style>.foobar{color:green;}</style>"));
1081
1082         equals( jQuery("#main").children().length, 1, "Make sure there is a child element." );
1083         equals( jQuery("#main").children()[0].nodeName.toUpperCase(), "STYLE", "And that a style element was inserted." );
1084
1085         QUnit.reset();
1086         // using contents will get comments regular, text, and comment nodes
1087         var j = jQuery("#nonnodes").contents();
1088         j.html(valueObj("<b>bold</b>"));
1089
1090         // this is needed, or the expando added by jQuery unique will yield a different html
1091         j.find('b').removeData();
1092         equals( j.html().replace(/ xmlns="[^"]+"/g, "").toLowerCase(), "<b>bold</b>", "Check node,textnode,comment with html()" );
1093
1094         jQuery("#main").html(valueObj("<select/>"));
1095         jQuery("#main select").html(valueObj("<option>O1</option><option selected='selected'>O2</option><option>O3</option>"));
1096         equals( jQuery("#main select").val(), "O2", "Selected option correct" );
1097
1098         var $div = jQuery('<div />');
1099         equals( $div.html(valueObj( 5 )).html(), '5', 'Setting a number as html' );
1100         equals( $div.html(valueObj( 0 )).html(), '0', 'Setting a zero as html' );
1101
1102         var $div2 = jQuery('<div/>'), insert = "&lt;div&gt;hello1&lt;/div&gt;";
1103         equals( $div2.html(insert).html().replace(/>/g, "&gt;"), insert, "Verify escaped insertion." );
1104         equals( $div2.html("x" + insert).html().replace(/>/g, "&gt;"), "x" + insert, "Verify escaped insertion." );
1105         equals( $div2.html(" " + insert).html().replace(/>/g, "&gt;"), " " + insert, "Verify escaped insertion." );
1106
1107         var map = jQuery("<map/>").html(valueObj("<area id='map01' shape='rect' coords='50,50,150,150' href='http://www.jquery.com/' alt='jQuery'>"));
1108
1109         equals( map[0].childNodes.length, 1, "The area was inserted." );
1110         equals( map[0].firstChild.nodeName.toLowerCase(), "area", "The area was inserted." );
1111
1112         QUnit.reset();
1113
1114         jQuery("#main").html(valueObj('<script type="something/else">ok( false, "Non-script evaluated." );</script><script type="text/javascript">ok( true, "text/javascript is evaluated." );</script><script>ok( true, "No type is evaluated." );</script><div><script type="text/javascript">ok( true, "Inner text/javascript is evaluated." );</script><script>ok( true, "Inner No type is evaluated." );</script><script type="something/else">ok( false, "Non-script evaluated." );</script></div>'));
1115
1116         jQuery("#main").html(valueObj("<script>ok( true, 'Test repeated injection of script.' );</script>"));
1117         jQuery("#main").html(valueObj("<script>ok( true, 'Test repeated injection of script.' );</script>"));
1118         jQuery("#main").html(valueObj("<script>ok( true, 'Test repeated injection of script.' );</script>"));
1119
1120         jQuery("#main").html(valueObj('<script type="text/javascript">ok( true, "jQuery().html().evalScripts() Evals Scripts Twice in Firefox, see #975 (1)" );</script>'));
1121
1122         jQuery("#main").html(valueObj('foo <form><script type="text/javascript">ok( true, "jQuery().html().evalScripts() Evals Scripts Twice in Firefox, see #975 (2)" );</script></form>'));
1123
1124         jQuery("#main").html(valueObj("<script>equals(jQuery.scriptorder++, 0, 'Script is executed in order');equals(jQuery('#scriptorder').length, 1,'Execute after html (even though appears before)')<\/script><span id='scriptorder'><script>equals(jQuery.scriptorder++, 1, 'Script (nested) is executed in order');equals(jQuery('#scriptorder').length, 1,'Execute after html')<\/script></span><script>equals(jQuery.scriptorder++, 2, 'Script (unnested) is executed in order');equals(jQuery('#scriptorder').length, 1,'Execute after html')<\/script>"));
1125 }
1126
1127 test("html(String)", function() {
1128         testHtml(bareObj);
1129 });
1130
1131 test("html(Function)", function() {
1132         testHtml(functionReturningObj);
1133
1134         expect(33);
1135
1136         QUnit.reset();
1137
1138         jQuery("#main").html(function(){
1139                 return jQuery(this).text();
1140         });
1141
1142         ok( !/</.test( jQuery("#main").html() ), "Replace html with text." );
1143         ok( jQuery("#main").html().length > 0, "Make sure text exists." );
1144 });
1145
1146 test("html(Function) with incoming value", function() {
1147         expect(20);
1148
1149         var div = jQuery("#main > div"), old = div.map(function(){ return jQuery(this).html() });
1150
1151         div.html(function(i, val) {
1152                 equals( val, old[i], "Make sure the incoming value is correct." );
1153                 return "<b>test</b>";
1154         });
1155
1156         var pass = true;
1157         div.each(function(){
1158                 if ( this.childNodes.length !== 1 ) {
1159                         pass = false;
1160                 }
1161         })
1162         ok( pass, "Set HTML" );
1163
1164         QUnit.reset();
1165         // using contents will get comments regular, text, and comment nodes
1166         var j = jQuery("#nonnodes").contents();
1167         old = j.map(function(){ return jQuery(this).html(); });
1168
1169         j.html(function(i, val) {
1170                 equals( val, old[i], "Make sure the incoming value is correct." );
1171                 return "<b>bold</b>";
1172         });
1173
1174         // Handle the case where no comment is in the document
1175         if ( j.length === 2 ) {
1176                 equals( null, null, "Make sure the incoming value is correct." );
1177         }
1178
1179         j.find('b').removeData();
1180         equals( j.html().replace(/ xmlns="[^"]+"/g, "").toLowerCase(), "<b>bold</b>", "Check node,textnode,comment with html()" );
1181
1182         var $div = jQuery('<div />');
1183
1184         equals( $div.html(function(i, val) {
1185                 equals( val, "", "Make sure the incoming value is correct." );
1186                 return 5;
1187         }).html(), '5', 'Setting a number as html' );
1188
1189         equals( $div.html(function(i, val) {
1190                 equals( val, "5", "Make sure the incoming value is correct." );
1191                 return 0;
1192         }).html(), '0', 'Setting a zero as html' );
1193
1194         var $div2 = jQuery('<div/>'), insert = "&lt;div&gt;hello1&lt;/div&gt;";
1195         equals( $div2.html(function(i, val) {
1196                 equals( val, "", "Make sure the incoming value is correct." );
1197                 return insert;
1198         }).html().replace(/>/g, "&gt;"), insert, "Verify escaped insertion." );
1199
1200         equals( $div2.html(function(i, val) {
1201                 equals( val.replace(/>/g, "&gt;"), insert, "Make sure the incoming value is correct." );
1202                 return "x" + insert;
1203         }).html().replace(/>/g, "&gt;"), "x" + insert, "Verify escaped insertion." );
1204
1205         equals( $div2.html(function(i, val) {
1206                 equals( val.replace(/>/g, "&gt;"), "x" + insert, "Make sure the incoming value is correct." );
1207                 return " " + insert;
1208         }).html().replace(/>/g, "&gt;"), " " + insert, "Verify escaped insertion." );
1209 });
1210
1211 var testRemove = function(method) {
1212         expect(9);
1213
1214         var first = jQuery("#ap").children(":first");
1215         first.data("foo", "bar");
1216
1217         jQuery("#ap").children()[method]();
1218         ok( jQuery("#ap").text().length > 10, "Check text is not removed" );
1219         equals( jQuery("#ap").children().length, 0, "Check remove" );
1220
1221         equals( first.data("foo"), method == "remove" ? null : "bar" );
1222
1223         QUnit.reset();
1224         jQuery("#ap").children()[method]("a");
1225         ok( jQuery("#ap").text().length > 10, "Check text is not removed" );
1226         equals( jQuery("#ap").children().length, 1, "Check filtered remove" );
1227
1228         jQuery("#ap").children()[method]("a, code");
1229         equals( jQuery("#ap").children().length, 0, "Check multi-filtered remove" );
1230
1231         // using contents will get comments regular, text, and comment nodes
1232         // Handle the case where no comment is in the document
1233         ok( jQuery("#nonnodes").contents().length >= 2, "Check node,textnode,comment remove works" );
1234         jQuery("#nonnodes").contents()[method]();
1235         equals( jQuery("#nonnodes").contents().length, 0, "Check node,textnode,comment remove works" );
1236
1237         // manually clean up detached elements
1238         if (method === "detach") {
1239                 first.remove();
1240         }
1241
1242         QUnit.reset();
1243
1244         var count = 0;
1245         var first = jQuery("#ap").children(":first");
1246         var cleanUp = first.click(function() { count++ })[method]().appendTo("#main").click();
1247
1248         equals( method == "remove" ? 0 : 1, count );
1249
1250         // manually clean up detached elements
1251         cleanUp.remove();
1252 };
1253
1254 test("remove()", function() {
1255         testRemove("remove");
1256 });
1257
1258 test("detach()", function() {
1259         testRemove("detach");
1260 });
1261
1262 test("empty()", function() {
1263         expect(3);
1264         equals( jQuery("#ap").children().empty().text().length, 0, "Check text is removed" );
1265         equals( jQuery("#ap").children().length, 4, "Check elements are not removed" );
1266
1267         // using contents will get comments regular, text, and comment nodes
1268         var j = jQuery("#nonnodes").contents();
1269         j.empty();
1270         equals( j.html(), "", "Check node,textnode,comment empty works" );
1271 });
1272
1273 test("jQuery.cleanData", function() {
1274         expect(14);
1275
1276         var type, pos, div, child;
1277
1278         type = "remove";
1279
1280         // Should trigger 4 remove event
1281         div = getDiv().remove();
1282
1283         // Should both do nothing
1284         pos = "Outer";
1285         div.trigger("click");
1286
1287         pos = "Inner";
1288         div.children().trigger("click");
1289
1290         type = "empty";
1291         div = getDiv();
1292         child = div.children();
1293
1294         // Should trigger 2 remove event
1295         div.empty();
1296
1297         // Should trigger 1
1298         pos = "Outer";
1299         div.trigger("click");
1300
1301         // Should do nothing
1302         pos = "Inner";
1303         child.trigger("click");
1304
1305         // Should trigger 2
1306         div.remove();
1307
1308         type = "html";
1309
1310         div = getDiv();
1311         child = div.children();
1312
1313         // Should trigger 2 remove event
1314         div.html("<div></div>");
1315
1316         // Should trigger 1
1317         pos = "Outer";
1318         div.trigger("click");
1319
1320         // Should do nothing
1321         pos = "Inner";
1322         child.trigger("click");
1323
1324         // Should trigger 2
1325         div.remove();
1326
1327         function getDiv() {
1328                 var div = jQuery("<div class='outer'><div class='inner'></div></div>").click(function(){
1329                         ok( true, type + " " + pos + " Click event fired." );
1330                 }).focus(function(){
1331                         ok( true, type + " " + pos + " Focus event fired." );
1332                 }).find("div").click(function(){
1333                         ok( false, type + " " + pos + " Click event fired." );
1334                 }).focus(function(){
1335                         ok( false, type + " " + pos + " Focus event fired." );
1336                 }).end().appendTo("body");
1337
1338                 div[0].detachEvent = div[0].removeEventListener = function(t){
1339                         ok( true, type + " Outer " + t + " event unbound" );
1340                 };
1341
1342                 div[0].firstChild.detachEvent = div[0].firstChild.removeEventListener = function(t){
1343                         ok( true, type + " Inner " + t + " event unbound" );
1344                 };
1345
1346                 return div;
1347         }
1348 });
1349
1350 test("jQuery.buildFragment - no plain-text caching (Bug #6779)", function() {
1351         expect(1);
1352
1353         // DOM manipulation fails if added text matches an Object method
1354         var $f = jQuery( "<div />" ).appendTo( "#main" ),
1355                 bad = [ "start-", "toString", "hasOwnProperty", "append", "here&there!", "-end" ];
1356
1357         for ( var i=0; i < bad.length; i++ ) {
1358                 try {
1359                         $f.append( bad[i] );
1360                 }
1361                 catch(e) {}
1362         }
1363     equals($f.text(), bad.join(''), "Cached strings that match Object properties");
1364         $f.remove();
1365 });