Inserting into the Middle of an Element’s Content

$("ul li:eq(2)).insertBefore($("<li>New Item</li>")); $("<p>Title</p>").before("#subtitle"); $("ul li:eq(2)).insertAfter($("<li>New Item</li>")); $("<p>Sub Title</p>").after("#title");

Often, you will want to add new items to the middle of an element’s content. For example, you might need to insert an item into the middle of a list or select or add a new paragraph right before an existing paragraph.

jQuery provides methods to insert content immediately before and after existing content. The new content is a sibling of the existing content.

To insert an element before an existing element, use existingObject.insertBefore(newContent) or newContent.before(existingObject) ...

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.