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> </ul> 

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.

 $('.list-5').after($('.list-1');); 

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

 $('.list-1').insertAfter('.list-5'); 

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.

    

via hongkiat.com http://rss.feedsportal.com/c/35261/f/656072/s/2c5bdee7/l/0L0Shongkiat0N0Cblog0Cjquery0Einsert0Eelement0Epart30C/story01.htm