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 ...

Get jQuery Pocket Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.