jQuery in Action
Setting element content
75
Sometimes, rather than inserting elements into other elements, we want to do
the opposite. Let's see what jQuery offers for that.
3.3.3 Wrapping elements
Another type of
DOM
manipulation that we'll often need to perform is to wrap an
element (or series of elements) in some markup. For example, we might want to
wrap all links of a certain class inside a
wrap all links of a certain class inside a
<div>
. We can accomplish such
DOM
mod-
ifications by using jQuery's
wrap()
command. Its syntax is as follows:
To wrap each link with the class
surprise
in a
<div>
with the class
hello
, we write
$("a.surprise").wrap("<div class='hello'></div>")
If we wanted to wrap the link in a clone of the first
<div>
element on the page:
$("a.surprise").wrap($("div:first")[0]);
When multiple elements are collected in a matched set, the
wrap()
method oper-
ates on each one individually. If we'd rather wrap all the elements in the set as a
unit, we can use the
unit, we can use the
wrapAll()
method instead:
Command syntax: wrap
wrap(wrapper)
Wraps the elements of the matched set with the passed HTML tags or a clone of the
passed element.
Parameters
wrapper
(String|Element) The opening and closing tags of the element with which to
wrap each element of the matched set, or an element to be cloned and server
as the wrapper.
wrap each element of the matched set, or an element to be cloned and server
as the wrapper.
Returns
The wrapped set.
The wrapped set.
Command syntax: wrapAll
wrapAll(wrapper)
Wraps the elements of the matched set, as a unit, with the passed HTML tags or a clone of
the passed element.
the passed element.
Parameters
wrapper
(String|Element) The opening and closing tags of the element with which to
wrap each element of the matched set, or an element to be cloned and server
as the wrapper.
wrap each element of the matched set, or an element to be cloned and server
as the wrapper.
Returns
The wrapped set
The wrapped set