jQuery in Action

78
CHAPTER 3
Bringing pages to life with jQuery
3.3.5 Cloning elements
One more way that we can manipulate the
DOM
is to make copies of elements to
attach elsewhere in the tree. jQuery provides a handy wrapper method for doing
so with its
clone()
command.
Making a copy of existing elements with
clone()
isn't useful unless we do some-
thing with the carbon copies. Generally, once the wrapped set containing the
clones is generated, another jQuery command is applied to stick them some-
where in the
DOM
. For example:
$('img').clone().appendTo('fieldset.photo');
This statement makes copies of all image elements and appends them to all
<fieldset>
elements with the class name
photo
.
A slightly more complex example is as follows:
$('ul').clone().insertBefore('#here');
This command chain performs a similar operation but the targets of the cloning
operation--all
<ul>
elements--are copied, including their children (it's likely
that any
<ul>
element will have a number of
<li>
children).
One last example:
$('ul').clone().insertBefore('#here').end().hide();
This statement performs the same operation as the previous example, but after
the insertion of the clones, the
end()
command is used to select the original
wrapped set (the original targets) and hide them. This emphasizes how the clon-
ing operation creates a new set of elements in a new wrapper.
Command syntax: clone
clone(copyHandlers)
Creates copies of the elements in the wrapped set and returns a new wrapped set that con-
tains them. The elements and any children are copied. Event handlers are optionally copied
depending upon the setting of the copyHandlers parameter.
Parameters
copyHandlers
(Boolean) If true, event handlers are copied. If false, or omitted,
handlers are not copied.
Returns
The newly created wrapped set.


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.