jQuery How-To: Creating And Inserting New Element (Part 3)

In this third part (click here for Part 1 and Part 2), we are going to continue our discussion on creating and inserting new element with jQuery. We have disccussed how to use the jQuery functions before() and after() to insert a new element before or after the specified element.

jQuery provides two similar functions. They are insertBefore() and insertAfter(), which sometimes lead to some confusion in their usage. How do these functions compare to before() and after()?

What’s the difference?

Both of these functions, before() and insertBefore() or insert() and insertAfter() are essentially does the same thing. But how they are executed is reversed. Let’s take a look at the following example for the detail.

We have HTML list, like so.

<ul id="list">
	<li class="list-1">Ut enim ad minim veniam.</li>
	<li class="list-2">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</li>
	<li class="list-3">Duis aute irure dolor in reprehenderit.</li>
	<li class="list-4">Sunt in culpa qui officia deserunt mollit.</li>
	<li class="list-5">Excepteur sint occaecat cupidatat non proident.</li>

Using the .after() we can write it this way to insert a new <li> element after the second list.

$('.list-2').after('<li class="new-elem">Hello World! This is the new element.</li>');

The code above will first tell jQuery to search for .list-2 and it will insert the new element afterwards. Using the .insertAfter() function, the opposite will be carried out. We will first create the new element then search the target container where the element should be inserted.

$('<li class="new-elem">Hello World! This is the new element.</li>').insertAfter('.list-2');

As mentioned, these functions will give us the same results, essentially.

Repositioning Element

Reather than create new elements, we can also reposition the existing elements in the document using these functions. Given the same HTML structure above, we can write it in this way to move, for example, the .list-1 to the bottom with .after() function.


Or using .insertAfter() function, we can write it this way.


They will return the same result, as shown in the following screenshot.

The same functionality also goes to .before() and .insertBefore().

Final Thought

Which function should be used, would depend on a case-by-case situation. Sometimes we might have to use insertAfter() and there are times when using after() is not a viable option.

Lastly, we have come to the end of our jQuery series, Creating and Inserting New Element. We hope that this can be a helpful reference for you. Thanks for reading and stay tuned for our next jQuery session.


Thoriq is a writer for Hongkiat.com with a passion for web design and development. He is the author of Responsive Web Design by Examples, where he covered his best approaches in developing responsive websites quickly with a framework.