jQuery in Action
Setting element content
73
<fieldset id="targets">
<legend>Target elements</legend>
<p><img src="dragonfly.png"/></p>
<p><img src="dragonfly.png"/></p>
<p><img src="dragonfly.png"/></p>
</fieldset>
The source fieldset contains two images: one with an
id
of
flower
, and one with an
id
of
car
. These image elements will serve as the source of the commands that we'll
apply. The target fieldset contains three
<p>
elements, each of which contains an
image. These paragraph elements will serve as the target of our commands.
Display this page, which can be found in the file chapter3/lab.move.and
.copy.html, in your browser. Leaving the appendTo radio button checked, click
the Execute button, which will execute code equivalent to the following:
the Execute button, which will execute code equivalent to the following:
$('#flower').appendTo('#targets p')
$('#car').appendTo('#targets p:first')
The first statement executes the
appendTo()
command on the flower image, spec-
ifying the three paragraph elements as the target. Because there's more than one
target element, we would expect the flower image to be copied. The second state-
ment issues the same command for the car image, but specifying only the first of
the paragraph elements as the target. Because there is only one target, we would
expect the car image to be moved.
target element, we would expect the flower image to be copied. The second state-
ment issues the same command for the car image, but specifying only the first of
the paragraph elements as the target. Because there is only one target, we would
expect the car image to be moved.
The display of figure 3.6, taken after the click of the Execute button, shows
that these expectations were correct.
It's clear from these results that when there are multiple targets, the source ele-
ment is copied, and when there is only a single target the source element is moved.
A number of related commands work in a fashion similar to
append()
and
appendTo()
:
prepend()
and
prependTo()
--Work like
append()
and
appendTo()
, but insert
the source element before the destination target's contents instead of after.
These commands can also be demonstrated in the Move and Copy Labora-
tory by clicking the PrependTo radio button before clicking Execute.
These commands can also be demonstrated in the Move and Copy Labora-
tory by clicking the PrependTo radio button before clicking Execute.
before()
and
insertBefore()
--Insert the element before the destination
elements instead of before the destination's first child.
after()
and
insertAfter()
--Insert the element after the destination ele-
ments instead of after the destination's last child.
Because the syntax of these commands is so similar to that of the append class of
commands, we won't waste the space to show individual syntax descriptions for
commands, we won't waste the space to show individual syntax descriptions for