jQuery in Action - Manning Publications
jQuery in Action - Manning Publications
jQuery in Action - Manning Publications
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
<strong>jQuery</strong> fundamentals<br />
That’s another use of the $() function; now let’s look at yet someth<strong>in</strong>g else it can<br />
do for us.<br />
1.3.4 Mak<strong>in</strong>g DOM elements<br />
As you can see by now, the authors of <strong>jQuery</strong> avoided <strong>in</strong>troduc<strong>in</strong>g a bunch of global<br />
names <strong>in</strong>to the JavaScript namespace by mak<strong>in</strong>g the $() function (which you’ll recall<br />
is merely an alias for the <strong>jQuery</strong>() function) versatile enough to perform many<br />
duties. Well, there’s one more duty that we need to exam<strong>in</strong>e.<br />
We can create DOM elements on the fly by pass<strong>in</strong>g the $() function a str<strong>in</strong>g that<br />
conta<strong>in</strong>s the HTML markup for those elements. For example, we can create a new<br />
paragraph element as follows:<br />
$("Hi there!")<br />
But creat<strong>in</strong>g a disembodied DOM element (or hierarchy of elements) isn’t all that useful;<br />
usually the element hierarchy created by such a call is then operated on us<strong>in</strong>g one<br />
of <strong>jQuery</strong>’s DOM manipulation functions. Let’s exam<strong>in</strong>e the code of list<strong>in</strong>g 1.1 as an<br />
example.<br />
List<strong>in</strong>g 1.1 Creat<strong>in</strong>g HTML elements on the fly<br />
<br />
<br />
Follow me!<br />
<br />
<br />
<br />
<br />
$(function(){<br />
$("Hi there!").<strong>in</strong>sertAfter("#followMe");<br />
});<br />
<br />
<br />
<br />
Follow me!<br />
<br />
<br />
This example establishes an exist<strong>in</strong>g HTML paragraph element named followMe C <strong>in</strong><br />
the document body. In the script element with<strong>in</strong> the section, we establish a<br />
ready handler B that uses the follow<strong>in</strong>g statement to <strong>in</strong>sert a newly created paragraph<br />
<strong>in</strong>to the DOM tree after the exist<strong>in</strong>g element:<br />
$("Hi there!").<strong>in</strong>sertAfter("#followMe");<br />
The result is shown <strong>in</strong> figure 1.3.<br />
We’ll be <strong>in</strong>vestigat<strong>in</strong>g the full set of DOM manipulation functions <strong>in</strong> chapter 3,<br />
where we’ll see that <strong>jQuery</strong> provides many means to manipulate the DOM to create<br />
nearly any structure that we may desire.<br />
B<br />
C<br />
Ready handler that<br />
creates HTML element<br />
Exist<strong>in</strong>g element<br />
to be followed<br />
13