O'Reilly logo

jQuery and JavaScript Phrasebook by Brad Dayley

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

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

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