Web Development with jQuery®

(Elliott) #1

Manipulating Content


and Attributes


jQuery is thorough; it provides everything you can imagine for working with content in the
DOM. In Chapter 2, “Selecting and Filtering,” you saw how jQuery made it easy to fetch
elements from the DOM via its fi ne-grained support for selecting and fi ltering selections.
Then in Chapter 3, “Events,” you saw how jQuery wraps and extends the W3C event model
to make it less verbose while also providing vastly more functionality. This chapter continues
the discussion of jQuery’s API components with an in-depth look at the methods that jQuery
makes available for manipulating content and attributes. No longer do you have to worry
about whether a browser supports the innerText or textContent properties, or the outerHTML
property, or what the standard DOM method of removing an element from a document is.
(You should know how to do those things anyway.) jQuery paves right over these verbose and
sometimes fragmented methods with a rock-solid API that just works.

This chapter covers how you can shuffl e DOM content around, doing things like replacing one
element with another, inserting new text or HTML, appending or prepending content, cloning
content, and getting rid of content.

It also covers how you manipulate attributes using jQuery, another area that jQuery makes
smooth and easy by providing all the methods you’d need to use in the library. Or maybe
you’ve had an occasion to want to save custom data with an element; jQuery provides this, too.

Setting, Retrieving, and Removing Attributes


Working with attributes is easy with jQuery. Like everything you do with jQuery, fi rst you
make a selection, and then after you’ve made a selection, you can do something with that
selection, like setting or accessing attributes. Setting attributes on a selection sets those attri-
butes on every element that you’ve selected. You can set the value of one or more attributes on

4


http://www.it-ebooks.info

Free download pdf