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"

src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.1.min.js">

</script>

<script type="text/javascript">

$(function () {

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

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

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

});

});

</script>

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

OUTPUT

jQuery add elements

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: