Web Development with jQuery®

(Elliott) #1

Manipulating HTML and Text Content (^) ❘ 103
Because jQuery always assumes the possibility of an array, it eliminates redundant code that has
historically always been required to iterate over an array or list of several elements. You can chain
methods onto one another, and you can perform complex operations on just one or many elements
at the same time. One thing you may ask yourself while working with jQuery is, how do I access
standard or de facto standard DOM methods and properties? In many cases, you don’t need to
directly access DOM properties or methods because jQuery provides equivalent and, in most cases,
less verbose methods that are designed to work seamlessly with jQuery’s chainable model of pro-
gramming. And not only are jQuery’s methods less verbose, they also attempt to fi x as many cross-
browser stability and reliability issues as possible.
One such property that jQuery replaces is the de facto standard innerHTML property. The innerHTML
property and many of Microsoft’s extensions to the DOM are on their way to standardization in the
HTML5 specifi cation. The innerHTML property is one of the few Microsoft extensions to the DOM
that has been ubiquitously adopted among browser makers.
Rather than relying exclusively on the implementation of Microsoft’s de facto standard
innerHTML property and similar properties, jQuery provides a variety of methods that assist you
in manipulating HTML and text content. This section discusses the following methods offered
in jQuery’s API:
➤ (^) The html() method sets or gets the HTML content of one or more elements.
➤ (^) The text() method gets or sets the text content for one or more elements.
➤ (^) The append() and prepend() methods let you append or prepend content. You will learn
about how these methods are actually better than the native de facto standard alternative,
innerHTML.
➤ (^) The after() and before() methods let you place content beside other elements (as opposed
to appending or prepending the content inside those elements).
➤ (^) insertAfter() and insertBefore() methods let you modify a document by taking
one  selection of elements and inserting those elements beside another selection of
elements.
➤ (^) The wrap(), wrapAll(), and wrapInner() methods give you the ability to wrap one or more
elements with other elements.
➤ (^) The unwrap() method removes a parent element, leaving its descendant elements in place of
the parent.
The following sections describe and demonstrate how the preceding methods work, to give you
expertise in understanding how content manipulation in jQuery works.


Getting, Setting, and Removing Content


The simplest methods that jQuery provides for content manipulation are the html() and text()
methods. If you make a selection and call one of these methods without any arguments, jQuery

http://www.it-ebooks.info

Free download pdf