jQuery in Action
Setting element content
71
A more complex use of this command identifies already-existing elements of
the
DOM
as the items to be appended. Consider the following:
$("p.appendToMe").append($("a.appendMe"))
This statement appends all links with the class
appendMe
to
<p>
elements with the
class
appendToMe
. The disposition of the original elements depends on the num-
ber of elements serving as the target of the append. If there is a single target, the
element is removed from its original location--performing a move operation of
the original element to a new parent. In the case where there are multiple tar-
gets, the original element remains in place and copies of it are appended to each
of the targets--a copy operation.
element is removed from its original location--performing a move operation of
the original element to a new parent. In the case where there are multiple tar-
gets, the original element remains in place and copies of it are appended to each
of the targets--a copy operation.
In place of a full-blown wrapped set, we can also reference a specific
DOM
ele-
ment, as shown:
var toAppend = $("a.appendMe")[0];
$("p.appendToMe").append(toAppend);
Whether the element identified by
toAppend
is moved or copied again depends
on the number of elements identified by
$("p.appendToMe")
: a move if one ele-
ment is matched, a copy if more than one element is matched.
If we want to move or copy an element from one place to another, a simpler
approach uses the
appendTo()
command, which allows us to grab an element and
move it somewhere else in the
DOM
.
A common semantic for most functions in this section is that an element will be
moved if the destination identifies only one target. If the destination denotes mul-
tiple target elements, the source element will remain in its original location and
be copied to each destination.
moved if the destination identifies only one target. If the destination denotes mul-
tiple target elements, the source element will remain in its original location and
be copied to each destination.
Command syntax: appendTo
appendTo(target)
Moves all elements in the wrapped set to the end of the content of the specified target(s).
Parameters
target
(String|Element) A string containing a jQuery selector or a DOM element. Each
element of the wrapped set will be appended to that location. If more than one
element matches a string selector, the element will be copied and appended to
each element matching the selector.
element of the wrapped set will be appended to that location. If more than one
element matches a string selector, the element will be copied and appended to
each element matching the selector.
Returns
The wrapped set.
The wrapped set.