Prepending to the Beginning of an Element’s Content

var newDiv = $("<div></div>"); $("body").append(newDiv); newDiv.append($("<p>Paragraph A</p>")); $("<p>Paragraph A</p>").appendTo("div");

jQuery provides methods to prepend content before the existing content in an element. For example, you can add list items, a table row, or paragraph text before existing list items, table rows, or text in a paragraph.

These methods are existingObject.prepend(newContent) and newContent.prependTo(existingObject). The existingObject can be an object you already have, or you can use a selector to specify the existing object.

For example, the following code creates a new <div> and appends it to body. Then it prepends two paragraphs ...

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.