O'Reilly logo

jQuery Pocket Reference by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required