Monday, December 29, 2008

[jQuery] Re: Undocumented move/copy behavior of append() et al.

Perfect :)

On Sun, Dec 28, 2008 at 11:45 PM, Dave Methvin <dave.methvin@gmail.com> wrote:
>
> Here's what I came up with, does it make sense?
> ------------------
> Content
>
> Most jQuery methods that accept "content" will accept one or more
> arguments of any of the following:
>
> * A DOM node element;
> * An array of DOM node elements;
> * A jQuery object;
> * A string representing HTML.
>
> Example:
> $("#div1").append(
> document.createElement("br"),
> $("#div2"), "<em>after div2</em>"
> );
>
> Auto-Cloning
>
> Content inserting methods (append, prepend, before, after, and
> replaceWith) behave differently depending on the number of DOM
> elements currently selected by the jQuery object. If there is only one
> element in the jQuery object, the content is inserted to that element;
> content that was in another location in the DOM tree will be moved by
> this operation. This is essentially the same as the W3C DOM
> appendChild method.
>
> http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#method-appendChild
>
> When multiple elements are selected by a jQuery object, these methods
> clone the content before inserting it to each element. Since the
> content can only exist in one location in the document tree, cloning
> is required in these cases so that the same content can be used in
> multiple locations.
>
> This rule also applies to the selector-insertion methods (appendTo,
> prependTo, insertBefore, insertAfter, and replaceAll), but the auto-
> cloning occurs if there is more than one element selected by the
> Selector provided as an argument to the method.
>
> When a specific behavior is needed regardless of the number of
> elements selected, use the .clone() or .remove() methods in
> conjunction with a selector-insertion method. This example will always
> clone #Thing, append it to each element with class OneOrMore, and
> leave the original #Thing unmolested in the document:
>
> $("#Thing").clone().appendTo(".OneOrMore");
>
> This example will always remove #Thing from the document and append it
> to .OneOrMore:
>
> $("#Thing").remove().appendTo(".OneOrMore");
>

No comments: