Append Vs. Prepend. What’s The Difference?

Elle D
3 min readMar 8, 2021

There are two functions given to us by JavaScripts’ library JQuery -that are similar(in functionality)yet different(in approach/ execution)at the same time. In this short blog we will talk about the two and explain their best uses.

We will start with Prepend.

Let’s say you have a div that is acting as a container. And in this container you already have existing elements. Here in our example, we have a div with an h2 tag inside of it with the words “eat”.

Left: editor/ Right: website

The goal is to use JS to manipulate this div and add an additional element to it WITHOUT removing the existing elements. And we specifically want to add this new element BEFORE the other elements currently in the div, which is the h2 tag.

This is where prepend comes into play.

First thing is to create a variable called “bear”. This variable will hold an image tag for us. Next, we can grab the div tag by its id or class name using our JQuery selector function $() and attach the prepend function. The prepend function will take the variable “bear” as an argument.

Left: prepend function added. /Right: result of prepend function.

And viola, we have an image of a bear! But notice that the bear is placed BEFORE the h2 tag. The prepend function will add something to the beginning without removing what’s already there! Pretty cool huh? 😎

Now, let’s talk about Append!

Well, append works the exact same way only it will add something to the end. To demonstrate this, we will create another variable and call it “beet”. This variable will also hold an image tag for us. In the same fashion, we will grab the div tag by its id or class name using our JQuery selector function $() and attach the append function. The append function will take the variable “beet” as an argument.

Left: append function added. /Right: result of append function.

And there you have it! Underneath the h2 tag we have an image of a beet thanks to the append function. The image was placed AFTER it. The append function will add something to the end without removing what’s already inside!

These two functions are perfect for manipulating elements in HTML using Javascript(with the library JQuery).

I hope you found this helpful and be on the look out for more blogs/vlogs next week. Until then….Happy coding Ya’ll 😜!

--

--