Skip to Main Content
jQuery Pocket Reference
book

jQuery Pocket Reference

by David Flanagan
December 2010
Intermediate to advanced content levelIntermediate to advanced
160 pages
3h 31m
English
O'Reilly Media, Inc.
Content preview from jQuery Pocket Reference

Chapter 3. Altering Document Structure

In Getting and Setting Element Content we saw the html() and text() methods for setting element content. HTML documents are represented as a tree of nodes rather than a linear sequence of characters, so insertions, deletions, and replacements are not as simple as they are for strings and arrays. The sections that follow explain the various jQuery methods for more complex document modification.

Inserting and Replacing Elements

Let’s begin with basic methods for insertions and replacements. Each of the methods demonstrated below takes an argument that specifies the content that is to be inserted into the document. This can be a string of plain text or of HTML, or it can be a jQuery object, Element, or text node. The insertion is made into, before, after, or in place of (depending on the method) each of the selected elements. If the content to be inserted is an element that already exists in the document, it is moved from its current location. If it is to be inserted more than once, the element is cloned. These methods all return the jQuery object on which they are called. Note, however, that after replaceWith() runs, the elements in the jQuery object are no longer in the document:

// Add content at end of the #log element $("#log").append("<br/>"+message); // Add section sign at start of each <h1> $("h1").prepend("§"); // Insert a rule before and after each <h1> $("h1").before("<hr/>"); $("h1").after("<hr/>"); // Replace <hr/> tags with <br/> tags ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

jQuery and JavaScript Phrasebook

jQuery and JavaScript Phrasebook

Brad Dayley
Beyond jQuery

Beyond jQuery

Ray Nicholus
Head First jQuery

Head First jQuery

Ryan Benedetti, Ronan Cranley

Publisher Resources

ISBN: 9781449398958Supplemental ContentErrata Page