jQuery: Add new Element before the Last Element

jQuery allows us to add new or existing elements anywhere in the DOM. All we need to do is identify the target element and use a jQuery inbuilt method to place elements before or are after the target element. Check out some DOM insertion methods here

Let us see an example where a paragraph is to be inserted before the last paragraph. We will be using the before method which will insert new content before each element, in the set of matched elements.

Consider the following HTML

jQuery Before

If we have to insert a new paragraph before the last paragraph, use the following code:

<script type="text/javascript"



<script type="text/javascript">

$(function () {

$("#btnOne").click(function () {

$('#divOne > p:last-child')

.before('<p>Dynamic Para</p>')




As you can see, we first use a selector which selects the last para in divOne and then use before method to insert a paragraph before the matched element


jQuery add elements

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: