index now works in reverse when passed a selector or undefined. fixes #3971
[jquery.git] / src / manipulation.js
1 jQuery.fn.extend({
2         text: function( text ) {
3                 if ( typeof text !== "object" && text != null )
4                         return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
5
6                 var ret = "";
7
8                 jQuery.each( text || this, function(){
9                         jQuery.each( this.childNodes, function(){
10                                 if ( this.nodeType != 8 )
11                                         ret += this.nodeType != 1 ?
12                                                 this.nodeValue :
13                                                 jQuery.fn.text( [ this ] );
14                         });
15                 });
16
17                 return ret;
18         },
19
20         wrapAll: function( html ) {
21                 if ( this[0] ) {
22                         // The elements to wrap the target around
23                         var wrap = jQuery( html, this[0].ownerDocument ).clone();
24
25                         if ( this[0].parentNode )
26                                 wrap.insertBefore( this[0] );
27
28                         wrap.map(function(){
29                                 var elem = this;
30
31                                 while ( elem.firstChild )
32                                         elem = elem.firstChild;
33
34                                 return elem;
35                         }).append(this);
36                 }
37
38                 return this;
39         },
40
41         wrapInner: function( html ) {
42                 return this.each(function(){
43                         jQuery( this ).contents().wrapAll( html );
44                 });
45         },
46
47         wrap: function( html ) {
48                 return this.each(function(){
49                         jQuery( this ).wrapAll( html );
50                 });
51         },
52
53         append: function() {
54                 return this.domManip(arguments, true, function(elem){
55                         if (this.nodeType == 1)
56                                 this.appendChild( elem );
57                 });
58         },
59
60         prepend: function() {
61                 return this.domManip(arguments, true, function(elem){
62                         if (this.nodeType == 1)
63                                 this.insertBefore( elem, this.firstChild );
64                 });
65         },
66
67         before: function() {
68                 return this.domManip(arguments, false, function(elem){
69                         this.parentNode.insertBefore( elem, this );
70                 });
71         },
72
73         after: function() {
74                 return this.domManip(arguments, false, function(elem){
75                         this.parentNode.insertBefore( elem, this.nextSibling );
76                 });
77         },
78
79         clone: function( events ) {
80                 // Do the clone
81                 var ret = this.map(function(){
82                         if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
83                                 // IE copies events bound via attachEvent when
84                                 // using cloneNode. Calling detachEvent on the
85                                 // clone will also remove the events from the orignal
86                                 // In order to get around this, we use innerHTML.
87                                 // Unfortunately, this means some modifications to
88                                 // attributes in IE that are actually only stored
89                                 // as properties will not be copied (such as the
90                                 // the name attribute on an input).
91                                 var html = this.outerHTML, ownerDocument = this.ownerDocument;
92                                 if ( !html ) {
93                                         var div = ownerDocument.createElement("div");
94                                         div.appendChild( this.cloneNode(true) );
95                                         html = div.innerHTML;
96                                 }
97
98                                 return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")], ownerDocument)[0];
99                         } else
100                                 return this.cloneNode(true);
101                 });
102
103                 // Copy the events from the original to the clone
104                 if ( events === true ) {
105                         var orig = this.find("*").andSelf(), i = 0;
106
107                         ret.find("*").andSelf().each(function(){
108                                 if ( this.nodeName !== orig[i].nodeName )
109                                         return;
110
111                                 var events = jQuery.data( orig[i], "events" );
112
113                                 for ( var type in events ) {
114                                         for ( var handler in events[ type ] ) {
115                                                 jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
116                                         }
117                                 }
118
119                                 i++;
120                         });
121                 }
122
123                 // Return the cloned set
124                 return ret;
125         },
126
127         html: function( value ) {
128                 return value === undefined ?
129                         (this[0] ?
130                                 this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
131                                 null) :
132                         this.empty().append( value );
133         },
134
135         replaceWith: function( value ) {
136                 return this.after( value ).remove();
137         },
138
139         domManip: function( args, table, callback ) {
140                 if ( this[0] ) {
141                         var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
142                                 scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
143                                 first = fragment.firstChild;
144
145                         if ( first )
146                                 for ( var i = 0, l = this.length; i < l; i++ )
147                                         callback.call( root(this[i], first), this.length > 1 || i > 0 ?
148                                                         fragment.cloneNode(true) : fragment );
149
150                         if ( scripts )
151                                 jQuery.each( scripts, evalScript );
152                 }
153
154                 return this;
155
156                 function root( elem, cur ) {
157                         return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
158                                 (elem.getElementsByTagName("tbody")[0] ||
159                                 elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
160                                 elem;
161                 }
162         }
163 });
164
165 jQuery.each({
166         appendTo: "append",
167         prependTo: "prepend",
168         insertBefore: "before",
169         insertAfter: "after",
170         replaceAll: "replaceWith"
171 }, function(name, original){
172         jQuery.fn[ name ] = function( selector ) {
173                 var ret = [], insert = jQuery( selector );
174
175                 for ( var i = 0, l = insert.length; i < l; i++ ) {
176                         var elems = (i > 0 ? this.clone(true) : this).get();
177                         jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
178                         ret = ret.concat( elems );
179                 }
180
181                 return this.pushStack( ret, name, selector );
182         };
183 });
184
185 jQuery.each({
186         remove: function( selector ) {
187                 if ( !selector || jQuery.multiFilter( selector, [ this ] ).length ) {
188                         if ( this.nodeType === 1 ) {
189                                 cleanData( this.getElementsByTagName("*") );
190                                 cleanData( [this] );
191                         }
192
193                         if ( this.parentNode ) {
194                                 this.parentNode.removeChild( this );
195                         }
196                 }
197         },
198
199         empty: function() {
200                 // Remove element nodes and prevent memory leaks
201                 if ( this.nodeType === 1 ) {
202                         cleanData( this.getElementsByTagName("*") );
203                 }
204
205                 // Remove any remaining nodes
206                 while ( this.firstChild ) {
207                         this.removeChild( this.firstChild );
208                 }
209         }
210 }, function(name, fn){
211         jQuery.fn[ name ] = function(){
212                 return this.each( fn, arguments );
213         };
214 });
215
216 jQuery.extend({
217         clean: function( elems, context, fragment ) {
218                 context = context || document;
219
220                 // !context.createElement fails in IE with an error but returns typeof 'object'
221                 if ( typeof context.createElement === "undefined" )
222                         context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
223
224                 // If a single string is passed in and it's a single tag
225                 // just do a createElement and skip the rest
226                 if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
227                         var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
228                         if ( match )
229                                 return [ context.createElement( match[1] ) ];
230                 }
231
232                 var ret = [], scripts = [], div = context.createElement("div");
233
234                 jQuery.each(elems, function(i, elem){
235                         if ( typeof elem === "number" )
236                                 elem += '';
237
238                         if ( !elem )
239                                 return;
240
241                         // Convert html string into DOM nodes
242                         if ( typeof elem === "string" ) {
243                                 // Fix "XHTML"-style tags in all browsers
244                                 elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
245                                         return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
246                                                 all :
247                                                 front + "></" + tag + ">";
248                                 });
249
250                                 // Trim whitespace, otherwise indexOf won't work as expected
251                                 var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();
252
253                                 var wrap =
254                                         // option or optgroup
255                                         !tags.indexOf("<opt") &&
256                                         [ 1, "<select multiple='multiple'>", "</select>" ] ||
257
258                                         !tags.indexOf("<leg") &&
259                                         [ 1, "<fieldset>", "</fieldset>" ] ||
260
261                                         tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
262                                         [ 1, "<table>", "</table>" ] ||
263
264                                         !tags.indexOf("<tr") &&
265                                         [ 2, "<table><tbody>", "</tbody></table>" ] ||
266
267                                         // <thead> matched above
268                                         (!tags.indexOf("<td") || !tags.indexOf("<th")) &&
269                                         [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
270
271                                         !tags.indexOf("<col") &&
272                                         [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
273
274                                         // IE can't serialize <link> and <script> tags normally
275                                         !jQuery.support.htmlSerialize &&
276                                         [ 1, "div<div>", "</div>" ] ||
277
278                                         [ 0, "", "" ];
279
280                                 // Go to html and back, then peel off extra wrappers
281                                 div.innerHTML = wrap[1] + elem + wrap[2];
282
283                                 // Move to the right depth
284                                 while ( wrap[0]-- )
285                                         div = div.lastChild;
286
287                                 // Remove IE's autoinserted <tbody> from table fragments
288                                 if ( !jQuery.support.tbody ) {
289
290                                         // String was a <table>, *may* have spurious <tbody>
291                                         var hasBody = /<tbody/i.test(elem),
292                                                 tbody = !tags.indexOf("<table") && !hasBody ?
293                                                         div.firstChild && div.firstChild.childNodes :
294
295                                                 // String was a bare <thead> or <tfoot>
296                                                 wrap[1] == "<table>" && !hasBody ?
297                                                         div.childNodes :
298                                                         [];
299
300                                         for ( var j = tbody.length - 1; j >= 0 ; --j )
301                                                 if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
302                                                         tbody[ j ].parentNode.removeChild( tbody[ j ] );
303
304                                         }
305
306                                 // IE completely kills leading whitespace when innerHTML is used
307                                 if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
308                                         div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
309
310                                 elem = jQuery.makeArray( div.childNodes );
311                         }
312
313                         if ( elem.nodeType )
314                                 ret.push( elem );
315                         else
316                                 ret = jQuery.merge( ret, elem );
317
318                 });
319
320                 if ( fragment ) {
321                         for ( var i = 0; ret[i]; i++ ) {
322                                 if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
323                                         scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
324                                 } else {
325                                         if ( ret[i].nodeType === 1 )
326                                                 ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
327                                         fragment.appendChild( ret[i] );
328                                 }
329                         }
330
331                         return scripts;
332                 }
333
334                 return ret;
335         }
336 });
337
338 function cleanData( elems ) {
339         for ( var i = 0, l = elems.length; i < l; i++ ) {
340                 var id = elems[i][expando];
341                 if ( id ) {
342                         delete jQuery.cache[ id ];
343                 }
344         }
345 }