jQuery in Action

jQuery fundamentals
11
1.3.4 Making DOM elements
It's become apparent by this point that the authors of jQuery avoided introducing
a bunch of global names into the JavaScript namespace by making the
$()
function
(which you'll recall is merely an alias for the
jQuery()
function) versatile enough to
perform many duties. Well, there's one more duty that we need to examine.
We can create
DOM
elements on the fly by passing the
$()
function a string
that contains the
HTML
markup for those elements. For example, we can create a
new paragraph element as follows:
$("<p>Hi there!</p>")
But creating a disembodied
DOM
element (or hierarchy of elements) isn't all that
useful; usually the element hierarchy created by such a call is then operated on
using one of jQuery's
DOM
manipulation functions.
Let's examine the code of listing 1.1 as an example.
<html>
<head>
<title>Follow me!</title>
<script type="text/javascript" src="../scripts/jquery-1.2.js">
</script>
<script type="text/javascript">
$(function(){
$("<p>Hi there!</p>").insertAfter("#followMe");
});
</script>
</head>
<body>
<p id="followMe">Follow me!</p>
</body>
</html>
This example establishes an existing
HTML
paragraph element named
followMe
c
in the document body. In the script element within the
<head>
section, we
establish a ready handler
b
that uses the following statement to insert a newly
created paragraph into the
DOM
tree after the existing element:
$("<p>Hi there!</p>").insertAfter("#followMe");
The result is as shown in figure 1.2.
Listing 1.1 Creating HTML elements on the fly
Ready handler that
creates HTML element
b
Existing element
to be followed
c


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

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