jQuery .prependTo() Method Examples

jQuery prependTo method is a very easy to use, if you want to insert content, text or html or both, into another element, before the content of the target element. By using it, you can easily add content, dynamic or static. In this article, I am going to share easy examples on using the prependTo() method in jQuery.

How to use jQuery prependTo Method

For the sake of the example, let us assume that we have two main divs with class “red” & “green” applied to them. Both these divs are held in another “container” div for easy manipulation. Apart from those two divs, we are also going have two individual buttons that will let you prependTo 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 prependTo method has been used on them dynamically.

Example: Using the .prependTo() method in jQuery to prepend content to the content of the target element (div)

Difference between jquery .prepend() and jquery .prependTo() methods

In jQuery, the .prepend() and .prependTo() methods have the same functionality  However, the main difference lies in the syntax. To be more precise, the syntax varies, in the placement of the content and target. Here’s an easy representation for your understanding:

Using the .prepend() method

Using the .prependTo() method

Where the new_content can be a div, an image, HTML content, etc. If you would like a technical explanation of the above, here it is:

When .prepend() is used, the container into which the content is inserted appears before the method.

When .prependTo() is used, the container into which the content is inserted appears after the method.

That’s it for now!

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

Share your thoughts, comment below now!



CommentLuv badge