jQuery in Action
Generating new HTML
31
2.2 Generating new HTML
Sometimes, we'll want to generate new fragments of
HTML
to insert into the
page. With jQuery, it's a simple matter because, as we saw in chapter 1, the
$
func-
tion can create
HTML
in addition to selecting existing page elements. Consider
$("<div>Hello</div>")
This expression creates a new
<div>
element ready to be added to the page. We
can run any jQuery commands that we could run on wrapped element sets of
existing elements on the newly created fragment. This may not seem impressive
on first glance, but when we throw event handlers, Ajax, and effects into the mix
(as we will in the upcoming chapters), we'll see how it can come in handy.
existing elements on the newly created fragment. This may not seem impressive
on first glance, but when we throw event handlers, Ajax, and effects into the mix
(as we will in the upcoming chapters), we'll see how it can come in handy.
Note that if we want to create an empty
<div>
element, we can get away with
a shortcut:
$("<div>")
As with many things in life, there is a small caveat: we won't be able to use this
technique to reliably create
technique to reliably create
<script>
elements. But there are plenty of techniques
for handling the situations that would normally cause us to want to build
<script>
elements in the first place.
To give you a taste of what you'll be able to do later (don't worry if some of it
goes over your head at this point), take a look at this:
$("<div class='foo'>I have foo!</div><div>I don't</div>")
.filter(".foo").click(function() {
alert("I'm foo!");
}).end().appendTo("#someParentDiv");
In this snippet, we first create two
<div>
elements, one with class
foo
and one
without. We then narrow down the selection to only the
<div>
with class
foo
and
bind an event handler to it that will fire an alert dialog box when clicked. Finally,
we use the
we use the
end()
method (see section 2.3.6) to revert back to the full set of both
<div>
elements and attach them to the
DOM
tree by appending them to the ele-
ment with the
id
of
someParentDiv
.
That's a lot going on in a single statement, but it certainly shows how we can
get a lot accomplished without writing a lot of script.
An
HTML
page that runs this example is provided in the downloaded code as
chapter2/new.divs.html. Loading this file into a browser results in the displays
shown in figure 2.5.
shown in figure 2.5.
On initial load, as seen in the upper portion of figure 2.5, the new
<div>
ele-
ments are created and added to the
DOM
tree (because we placed the example
Identical to $("<div></div>")
and $("<div/>")
and $("<div/>")