jQuery .prepend() Method Examples

In jQuery, Tips and Tricks by March 24th, 2013

361 Views

If you ever wanted to Insert content (text or html or both), specified by the parameter, to the beginning of each element in the set of matched elements, then using the jQuery prepend method is an excellent option. In this article, I am going to share easy examples on how to use the .prepend() method.

How to use jQuery prepend method

Bacially, the prepend() method in jQuery adds the content before the content of the target. So let’s see how to use it with a simple, easy to follow example. This example assumes that we have 2 divs with class “red” & “green” applied to them. Apart from that, these divs are held in another “container” div for easy manipulation. So what we are going to do is have 2 individual buttons that will let you prepend the red div to green div and vice-versa.  We also have another button that will reset the divs back to their original state, once the prepend method has been used on them dynamically.

Example: Using the prepend method in jQuery to add content before the content of the target begins

Simple, isn’t it?

Do you know of any other ways to use the jQuery prepend() method? Feel free to suggest by commenting below.